Howto to resize (thumbnail) on upload file. How to reach the more easy example, for dummies.
Howto to resize (thumbnail) on upload file. How to reach the more easy example, for dummies.
Hi Allan,
I came back to question: to resize (thumbnail) on upload file. I take as reference
http://beqi.datatables.net/forums/discussion/27034/document-upload-path . On it, the user MarianH , add a code to create thumbnails, but she use Mjoin on image, and therefore it done that your code to be complex. I´ve tried adapt the example to more basic, without Mjoin ( I don't use Mjoin) but don't get.
Any help will be appreciate.
Thank you in advance!
Eduardo
PD: about resize image.
I invite you to think to support resize features on next versions of Datatables ( is only my request). Nowadays Android or iPhone devices have a minimal picture of 1,8 Mb and 2,37 Mb of size, If you work with pictures on table, both bandwidth of devices ( if you treat table with pictures) as server storage can be a big problem.
<?php
/*
* Example PHP implementation used for the index.html example
*/
// DataTables PHP library
include( "../../../../_DataTables/php/DataTables.php" );
// vars
$site=$_POST['site'];
$idioma='es';
// TRY CODE.START
// below function, I think that it's OK ( don't need changes )
function make_thumb($src, $dest, $desired_width) {
if (!file_exists($dest)) {
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
$desired_height = floor($height * ($desired_width / $width));
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
imagejpeg($virtual_image, $dest);
}
}
// below function ( need changes ) because it was design to used Mjoin on image.
// If you don't use Mjoin on image, how to make more simple? (if you dont need Mjoin on image)
function thumbnails($db, $values) {
$files = array();
// HERE (below lines) If I don't use Mjoin of image, what i've to modify on below loops?
// "image-many-count" (unknown params for me) , need change? , below:
for ($i=0 ; $i<=$values["image-many-count"]-1 ; $i++ ) {
$result = $db->sql('SELECT system_path FROM files WHERE id='.$values["image"][$i]["id"].';' );
while ($row = $result->fetch()) {
$files[] = $row['system_path'];
}
}
foreach ($files as &$file) {
$path_parts = pathinfo($file);
// 'dirname' and 'basename' , (unknown params for me) , need change? , below:
make_thumb($file, $path_parts['dirname']."/thumbnails/".$path_parts['basename'], 75);
}
}
// TRY CODE.END
// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Mjoin,
DataTables\Editor\Join,
DataTables\Editor\Upload,
DataTables\Editor\Validate;
// Build our Editor instance and process the data coming from _POST
Editor::inst( $db, 'chef_recomd' )
->fields(
Field::inst( 'site' )->validator( 'Validate::notEmpty' ),
Field::inst( 'id_lang' )->validator( 'Validate::notEmpty' ),
Field::inst( 'nombre' )->validator( 'Validate::notEmpty' ),
Field::inst( 'condimentos' ),
Field::inst( 'es_un' )->validator( 'Validate::notEmpty' ),
Field::inst( 'alergeno' )->validator( 'Validate::notEmpty' ),
Field::inst( 'precio' )->validator( 'Validate::numeric' ),
Field::inst( 'prec_terraza' )->validator( 'Validate::numeric' ),
Field::inst( 'nota_item' ),
Field::inst( 'image' )
->setFormatter( 'Format::nullEmpty' )
->upload(
Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/upload/__ID__.__EXTN__' )
->db( 'files', 'id', array(
'site' =>$site,
'filename' => Upload::DB_FILE_NAME,
'filesize' => Upload::DB_FILE_SIZE,
'web_path' => Upload::DB_WEB_PATH,
'system_path' => Upload::DB_SYSTEM_PATH
) )
->validator( function ( $file ) {
return$file['size'] >= 3500000 ?
"Files must be smaller than 3500K o 3,5 Mb" :
null;
} )
->dbClean( function ( $data ) {
// Remove the files from the file system
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
unlink( $data[$i]['system_path'] );
}
// Have Editor remove the rows from the database
return true;
} )
->allowedExtensions( array( 'png', 'jpg', 'gif' ), "Please upload an image file" )
),
Field::inst( 'creado_date' )
)
->on('postCreate', function ($editor, $id, $values, $row) use ($db){
thumbnails($db, $values);
//var_dump($values); // ONLY TEST
})
->on('postEdit', function ($editor, $id, $values, $row) use ($db){
thumbnails($db, $values);
//var_dump($values); // ONLY TEST
})
->where( 'site', $site)
->where( 'id_lang', $idioma )
->process( $_POST )
->json();
This question has accepted answers - jump to:
Answers
Thanks for posting your code - I'm sure others will really appreciate it!
Of images? Do you mean a pre-built function similar to your one above that will resize images to thumbnails?
Allan
Hi Allan,
Yes, resize images on server-side
NOTE: the code (above) currently NOT WORK. It have a problema (unknown for me), I ´m working to solve, but I think that the problema are when I pass the values on the function thumbnails($db, $values) on 114 and 119 lines.
The ($values) array, have not none information of upload file. If you do var_dump($values) don't show any upload file information.
How I can to see the upload file Information ( the array that keep the information of upload file ) . Please, can you tell me how to show the array taht have the upload file information with the command var_dump() , can you show me an example?
Thank you Allan!
Best Regards
Eduardo.
You are correct - the
postCreate
server-side event does not have any information about the uploaded file. It is the upload action callback that is called async to the rest of the form that has the file information.The documentation shows how you can provide a custom callback that will move / modify or otherwise handle the files. It is in that callback that you would create the thumbnails as you have access to the uploaded file there.
Allan
Thank you Allan,
Now, I understand and I will work on base to the documentation that you appointed.
Best regards, Eduardo.
Hi Allan,
I've used code example of custom actions from your documentation and I got a error (below). How I can to solve?
Thank you, Eduardo
error:
My code:
Hi,
As the error says, you can't use
DB_WEB_PATH
orDB_SYSTEM_PATH
when you provide a custom action since it doesn't know where you are writing the file to!What you would need to do is do an UPDATE on the database row in question with the web path that your custom action sets.
Allan
Hi Allan,
Thank you for you help. I´ve add an UPDATE and I´ve make a progress, but now have two issues, perhaps is a "collateral issues" when you use upload custom actions:
Any help are welcome.
Thank you,
Eduardo
Row of table ( 675 is a ID row on table):
My code:
If you ssh into the server and type
ls -l
in theupload
directory - what does it show?Thanks,
Allan
Hi Allan,
Thank you for you help,
Here the output of command, you can see that when use "standard uploaded file" the name of file uploaded changes to ID of table row inserted (files until 10 mars). When you use "upload custom action" - my code - the name of file uploaded no change (files from 16 mars) but it changes on "web_path" , "system_path" fields of the table (see below). I think this is the razon which the image is not found, right?
Let me know,
Eduardo
And the table is
Correct! You need to change the second argument being passed to
move_uploaded_file()
. Currently you are telling it to store the file with its name! You need to change it to be id plus extension.Allan
Hi Allan,
Thank you for you help.
We are give a step more!. Now the name of file is rename on server hosting with ID of row inserted (below PHP code) but is not renamed on DB table. The field "filename" keep your original name...this can be a problem?, because the images (pictures ) don't show neither a form (when pickup a file) nor on table, on both (form and table) appear a rectangle empty. With Dev tools (on table) appear "undefined" (see below):
Thank you in advance,
Eduardo
if manualy (from dev tools) i write /upload/571.jpg , the picture is showed on table:
JSON output : ( note: "web_path" field don't came. this is a problem? )
And related issue:
When you select a row and give Delete button , appear a error : https://datatables.net/manual/tech-notes/12., but if you give again Delete , the row is remove and close de dialog and the file is not remove form server. Any idea?
Current PHP code, related to upload()
Current JS code, related to image (form and table):
Change:
To be:
The problem was that
web_path
andsystem_path
were not being read since they weren't in the list of options. That will jsut set them to be an empty string.Allan
Hi Allan, you are great!
Now the image on the form and also on table is showed (solved!)
Also, the rezise function now works!, This fuction make_thumb() create a thubnails on folder on server. Also I add two new fields on DB table ("webPathTumbs1" and "sysPathThumbs1) , this action allow to recover the thumbnails files (lower size) when the table (columns) is created, so the performance is better ( on 3G mobile enviroment).
Only a final question to reach the goal:
- When click on Delete button on table, how to remove both files? (file uploaded and thunbnail created) . I´ve try but give me an error ( please see my wrong code, below, line 78).
Any idea?
Thank you in advance!
Eduardo
What's the error that the unlink function gives?
Allan
Hi Allan,
Thank you for you help.
Unlink function give none errors and it works, but only remove the file on 'system_path' (path indicated on unlink function).
I want to remove the file on two locations (or all locations if I create more than one thumbnails) . When I click on Delete button I want to remove the files on : 'system_path' , 'system_path_thumb', 'system_path_thumb_1', ...
How to remove at once all files if are on more than one location?
My best greetings,
Eduardo
So the second
unlink
doesn't result in any errors? Do you have all PHP warnings turned on?Allan
Hi Allan,
My apologies, unlink function works and delete files, has been my error on my tests. Current code that works:
I´m goint to try with 3 folders (/upload, /upload_thumb1, /upload_thumb2) and if everything works, i will post the final code.
Thank you so much!!
Eduardo
Excellent - good to hear that its all looking good now.
Allan
Hi Allan,
Your help was decisive for to reach the goal, so thank very much.
I post de FINAL CODE (below) that works on my example. It is not a elegant code (sure it can doing better) but it works.
My best regards,
Eduardo
Hi Allan,
One more step beyond, can i use "where conditions" on upload file?.
I mean: upload file JSON give me all files that I´ve uploaded , when I use "upload custom action" ( above thread), but I need only files (rows) that match with the $site variable. P.e:
How to get files (rows) that ONLY belong to site: "342800010" ?
Where condition ( above thread) work fine with [data] , but not with [files_chef_recomd] (see below JSON outputs)
Thank you in advance
Eduardo
JSON output from [files_chef_recomd]
JSON output from [data]
Hi Allan,
Right now, I´ve seen that 1.6.2 release include "where" sentence on upload file, congrats!!
Please, can you tell me a example of use?
If there are to add another "where" , please can you said me what line should to go ? You can to use above code as reference to point the line, it will be helpful for me.
Thank you !
Eduardo
In between line 105 and 106. It is a method of the
Upload
class so it could go anywhere on theUpload
chain, but that's as good as anywhere.Allan
Hi Allan;
As your comment, a first test of "where" sentence on upload file with custom action with v1.6.2 don't work on my code, perhaps I don't do it well. Can you review my syntax? (line 44)
JSON output (files_chef_recomd): should to show only site = 342800010, but not.
The
where()
method forUpload
needs to be given as a function:That assumes that you are posting the
site
parameter to the server with the upload action.Allan
Hi Allan,
I´sorry this is new for me, so let me go to step-by-step.
1. I´ve try your sintax, but don't get result.
2. I´ve try with a fixed value, on line ( //ONLY for Test) , but don't get result. Should to work?
3. I think that when step 2 work, i will review posting "site" parameter
Thank you!
Greetings
JSON output (files_chef_recomd) whith above $q->where( 'site', "342800010" )
Did you update the PHP libraries to 1.6.2 as well? That looks like it should work!
Could you add
->debug( true )
immediately before the->process( ... )
method call and then show me the JSON that the server is responding with when the table is initially loaded? It will contain the SQL statements that the libraries are using.Allan
Hi Allan,
Thank for you help.
I´ve follow your comments , but " ->debug( true )" , adds nothing new , i mean, is the same that see with Google dev tools (sorry , perhaps is my fault ).
So, I´ve used https://debug.datatables.net/ and I show you:
libraries that currently I used (Software)
JSON output that give me your Javascript snippet ( i will hope that it will be that you need).
Greetings!
PD: I´ve to run Javascript snippet keep above where line:
1.Software:
2.JSON output
What is the debug code which the debugger gave you?
Could you also show us the PHP you are using please? Make sure you add it before you call
process()
.Allan
Hi Allan,
Thank you for you help
My apologies, I had a mistake on my call to php file. I'm sorry, debug( ) now works! , output below.
Additional info: I´m used https protocol on *.html files, if that helps.
About PHP version: 5.6.19 , on Headers (Chrome DevTools ) :
JSON output , with ->debug( true ):