Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 795
Tenatious Avatar asked Feb 12 '13 14:02

Tenatious


People also ask

What drag means in slang?

something/someone boring/annoying. something that slows progress.

What is drag LGBT?

Drag is where individuals dress up as a different gender, primarily for short periods of time, which differentiates the practice from people who are trans and change their gender socially and/or legally.


1 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...

like image 73
wildhaber Avatar answered Oct 19 '22 12:10

wildhaber