Uploadify – How to Rename an Uploaded File

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!