I’ve recently got to grips with Uploadify – a great little jQuery plugin that allows you to simply upload images in a crazily easy to use form. However the images will overwrite, and I wanted to prevent this by renaming it if there was a clash.
This wasn’t too difficult. In uploadify.php, you will find the code that actually deals with the moving of the uploaded file.
Simply adding a file_exists function to the code allowed me to check if I needed to rename the file. Adding a number to the end of it and counting up until it no longer had a clash does the trick. You can also plug in some more stuff here, like creating thumbnails.
if(file_exists($targetFile)){ //we need to rename the file here to avoid a clash. //Add a number to the end until it doesn't clash $info = pathinfo($targetFile); $file_name = basename($targetFile,'.'.$info['extension']); $count=1; while(file_exists($file_name."_".$count.$info['extension'])){ ++$count; } $targetFile = $info['dirname'].'/'.$file_name.'_'.$count.'.'.$info['extension']; } move_uploaded_file($tempFile,$targetFile);
Anyway, this still causes a problem. if you are using the onComplete function call, you will find that the fileObj.name returns the original file name, not the new one. The solution? Read the response instead, which will contain the original file name.
'onComplete' : function(event, ID, fileObj, response, data){ //fileObj will return the original file name, so use response instead. $('#image_thumbnail').attr('src', response).show(); }
I hope that helps someone and saves them the time it took me to figure it out!
Hi.. I know you write this long time ago… but is it possible to gimme some adivice? My code ‘onComplete’: processe the name change on uplodify.php and the database change on insert2.php, I did not understand what Am I suppose to change on my code. What should I change for #image_thumbnail and attr(‘src’,. Tks a lot
Hi Paulo, the $(#image_thumbnail).attr(… line is needed if you wanted to know what the filename was when the jQuery calls back to let you know the file upload was completed successfully. If you don’t need to know this, then you don’t need this bit of code. I added to my jQuery code it as I needed to know after the file had been uploaded what the name was.