Search code examples
phpajaxuploader

Adding Random Number to Uploaded File


I'm using Valum's Ajax-Uploader script to upload files to my server. Because there's a good chance of the uploaded files have the same name I add a random number to the filename. The problem is that the ajax uploader is returning the original filename into the input[type=text] instead of the new filename with the random number added. I've tried echo $file; instead of echo "success"; , but all that happens is that the file is uploaded, and the script returns with the pop-up error.

jQuery(function() {
    var url = "http://example.com/uploads/samples/";
    var button = jQuery('#up');
    new AjaxUpload(button, {
        action: 'upload.php',
        name: 'upload',
        autoSubmit: true,
        onSubmit: function(file, ext) {
            // do stuff while file is uploading
        },
        onComplete: function(file, response) {
            if (response === "success") {
                $('input[type=text]').val(url + file);
            } else {
                jAlert('Something went wrong!', 'Error!');
            }
        }
    });
});

upload.php

<?php
    $uploaddir = '/path/to/uploaddir/'; 
    $file = basename($_FILES['file']['name']);

     if($_FILES['file']['name']) {
      $file = preg_replace('/\s+/', '_', $file);
      $rand = rand(0000,9999);

      if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $rand . $file)) { 
            echo "success";
        } else {
            echo "error";
        }
    }
?>

Solution

  • Client code and server code exist completely independently of each other. Basically, your JavaScript code has no way of knowing what your PHP code just did. url doesn't update automatically when you change it in the PHP file.

    An alternate solution would be to have your PHP code echo the new filename, or echo an error message.

    For example:

    PHP

    <?php
    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $rand . $file)) {   
        // Everything went well! Echo the dollar sign ($) plus the new file name
        echo '$' . $_FILES['file']['tmp_name'], $uploaddir . $rand . $file;   
    } else {  
        echo "error";  
    }  
    ?>
    

    JS

    onComplete: function(file, response) { 
        // If the first character of the response is the "$" sign
        if (response.substring(0,1) == "$") { 
            $('input[type=text]').val(response.substring(1));
        } else { 
            jAlert('Something went wrong!', 'Error!'); 
        } 
    }