File drag and drop event in jquery

家住魔仙堡 提交于 2019-12-03 12:34:44

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);

Plupload is a jQuery plugin to do multifile upload and has HTML 5 drag/drop from desktop supported. Its easy to configure, check http://www.plupload.com/example_queuewidget.php

If you don't want upload functionality, check out the following:

(Drag and drop from desktop and store into local storage) http://jsdo.it/hirose31/7vBK

(jQuery FileDrop - HTML5 Drag 'n Drop Files) https://github.com/weixiyen/jquery-filedrop

(HTML5) http://www.html5rocks.com/en/features/file , http://xquerywebappdev.wordpress.com/2010/05/21/drag-n-drop-from-desktop-jquery-plugin/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!