Search code examples
phpajaxdropzone.jsdropzone

How to access a file after it was uploaded with Dropzone.js and PHP


I would like to access a file after it was uploaded to the server via dropzone.js (v5) and PHP, i.e. I'd like to retrieve the file URL. How can I get it?

form.php:

<form action="upload.php" class="dropzone" enctype="multipart/form-data">
    <div class="fallback">
        <input name="file" type="file" multiple />
    </div>
</form>

<script src="/js/dropzone.js"></script>
<script>
    Dropzone.autoDiscover = false;
    $('.dropzone').dropzone({
        init: function () {
            this.on("complete", function (file) {
                runthisfunction();
            }) // end on complete
        }
    }); 
</script>

upload.php:

<?php
if (!empty($_FILES)) {
    $random = randomString(18);
    $tempFile = $_FILES['file']['tmp_name'];          
    $name = $_FILES['file']['name'];
    $fileExt = strtolower(substr(basename($name), strrpos(basename($name), ".") + 1)); 
    $newname = $random.'.'.$fileExt;
    move_uploaded_file($tempFile,"images/$newname");
} // end if files not empty
?>

I have tried retrieving the uploaded file URL via the file object, but no success:

this.on("complete", function (file) {
    console.log(file);
    console.log(file.dataURL);
    console.log(file.name);
}) // end on complete

Since the file is uploaded with PHP and renamed within the upload.php, I believe I would need to "POST" this filename somehow to another file and then retrieve it back. How can I do that?


Solution

  • Your intuition about needing to get the filename back from the server is correct. There's a simple example in the Dropzone FAQ which shows the basic idea.

    1) Your server has to respond to the upload POST with the details of where it put the file - eg URL, filename, path, etc. So in your case, at the end of your PHP code, you'd need to do something like:

    // ... rest of your PHP ...
    move_uploaded_file($tempFile,"images/$newname");
    
    // Let the browser/JS know we are sending a JSON response back.  Make sure there 
    // is no output before this.
    header('Content-type: application/json');
    echo json_encode([
        'status' => 'OK',  // Not required, but maybe useful
        'image'  => "images/$newname",
    ]);
    

    2) In your JS, you need to accept that response from the server, and do something with it. The Dropzone docs show for the success event:

    The file has been uploaded successfully. Gets the server response as second argument.

    This sounds like the one we need. So replace your complete handler with one for success, and add a 2nd argument:

    this.on("success", function (file, response) {
        console.dir(response);
        // response.image will be the relative path to your uploaded image.
        // You could also use response.status to check everything went OK,
        // maybe show an error msg from the server if not.
    });
    

    The Dropzone FAQ item I linked to above shows using an .emit() method to display the image, I'm not familiar with that and it doesn't seem to be described in the docs. Try it, maybe that works and suits your needs. If not, you could do something like:

    // Maybe you have an <img class='thumbnail'> in your HTML, ready to show the upload
    $('.thumbnail').attr('src', response.image).fadeIn();