Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File drag and drop event in jquery

I'm trying to find a way of letting users drag and drop individual files into an area on my page that can then get submitted along with all my other form data.

In my research I've found multiple "drag and drop" upload scripts but they all do way, way too much. I want to handle the actual uploading myself and just provide a way for users to upload files without hitting the browse button.

Is there an event in jquery (or something similar) that I should be looking for?

Any help is much appreciated!

like image 867
Jon Avatar asked Jul 07 '11 00:07

Jon


People also ask

How do you drag and drop a file?

How do I Drag and Drop? By default, if you left-click and HOLD the left mouse or touchpad button while moving your mouse pointer to a different folder location on the same drive, when you release the left mouse button the file will be moved to the new location where you released the mouse button.

What is drop file?

dropfile (plural dropfiles) (computing, dated) A file used by a bulletin board system (BBS) to pass information about the BBS itself and the current user to an external door.


1 Answers

I came across this question while researching some AJAX file upload techniques.

I created a drag and drop upload script today (its still in proof of concept stage but heres the basic steps that I took.

$('drag-target-selector').on('drop', function(event) {

 //stop the browser from opening the file
 event.preventDefault();

 //Now we need to get the files that were dropped
 //The normal method would be to use event.dataTransfer.files
 //but as jquery creates its own event object you ave to access 
 //the browser even through originalEvent.  which looks like this
 var files = event.originalEvent.dataTransfer.files;

 //Use FormData to send the files
 var formData = new FormData();

 //append the files to the formData object
 //if you are using multiple attribute you would loop through 
 //but for this example i will skip that
 formData.append('files', files[0]);

 }

now you can send formData to be processed by a php script or whatever else you want to use. I didn't use jquery in my script as there a lot of issues with it it seemed easier to use regular xhr. Here is that code

var xhr = new XMLHttpRequest();
    xhr.open('POST', 'upload.php');
    xhr.onload = function() {
            console.log(xhr.responseText);

    };


    xhr.upload.onprogress = function(event) {
            if (event.lengthComputable) {
                    var complete = (event.loaded / event.total * 100 | 0);
                    //updates a <progress> tag to show upload progress
                    $('progress').val(complete);

            }
    };

xhr.send(formData);
like image 104
Paul Mulgrew Avatar answered Oct 25 '22 05:10

Paul Mulgrew