Drag & Drop File Upload

So I'm struggling a bit to find what I'm looking for and how to implement it.

I have a basic PHP file uploader working, in that a user presses a custom upload button, selects a file and then using JS, it checks for a change (Ie. the user selecting a file) and then submits the form which uploads the image fine.

What I also want now is a drag & drop to upload area. So the user can drag an image from their file explorer and drop it in a designated place (not the whole page) and then once that image has been dropped for the form to submit automatically with their image and use the same PHP processing.

Is this possible and realistic?

Answers


This is absolutely realistic and possible without using any third parties plugin.

The following snippets should give you an idea of how it could work:

Drop area

$(".drop-files-container").bind("drop", function(e) {
    var files = e.originalEvent.dataTransfer.files;
    processFileUpload(files); 
    // forward the file object to your ajax upload method
    return false;
});

the processFileUpload()-Method:

function processFileUpload(droppedFiles) {
         // add your files to the regular upload form
    var uploadFormData = new FormData($("#yourregularuploadformId")[0]); 
    if(droppedFiles.length > 0) { // checks if any files were dropped
        for(var f = 0; f < droppedFiles.length; f++) { // for-loop for each file dropped
            uploadFormData.append("files[]",droppedFiles[f]);  // adding every file to the form so you could upload multiple files
        }
    }

 // the final ajax call

       $.ajax({
        url : "upload.php", // use your target
        type : "POST",
        data : uploadFormData,
        cache : false,
        contentType : false,
        processData : false,
        success : function(ret) {
                 // callback function
        }
       });

 }

form example

<form enctype="multipart/form-data" id="yourregularuploadformId">
     <input type="file" name="files[]" multiple="multiple">
</form>

Feel free to use something like this as a starting point. The browser support of this you can find here http://caniuse.com/#feat=xhr2

Of course you can add any extras you wish like progress bar, preview, animation...


Need Your Help

ini_set() scope of effect?

php php-ini

I've had index.php and several files which cascading include,something like this.

Using git commands in a TeamCity Build Step

git teamcity teamcity-7.0

One of my TeamCity v7.0 build projects relies on using a diff between the current development branch and the master branch to determine what needs to be run. I've written a small script that uses