在jquery中文件拖放事件

Jon*_*Jon 9 javascript ajax upload jquery

我试图找到一种方法让用户将单个文件拖放到我页面上的某个区域,然后可以将其与所有其他表单数据一起提交.

在我的研究中,我发现了多个"拖放"上传脚本,但它们都做得太多了.我想自己处理实际上传,只是为用户提供了一种上传文件的方式,而无需点击浏览按钮.

在jquery(或类似的东西)中是否有我应该寻找的事件?

任何帮助深表感谢!

小智 19

我在研究一些AJAX文件上传技术时遇到了这个问题.

我今天创建了一个拖放上传脚本(它仍然是概念证明阶段,但是我采取了基本的步骤.

$('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]);

 }
Run Code Online (Sandbox Code Playgroud)

现在你可以发送formData来处理php脚本或你想要使用的任何其他内容.我没有在我的脚本中使用jquery,因为它有很多问题,使用常规xhr似乎更容易.这是代码

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);
Run Code Online (Sandbox Code Playgroud)


Pan*_*al. 6

Plupload是一个jQuery插件,用于执行多文件上传,并支持从桌面拖放HTML 5.它易于配置,请查看http://www.plupload.com/example_queuewidget.php

如果您不想上传功能,请查看以下内容:

(从桌面拖放到本地存储中) http://jsdo.it/hirose31/7vBK

(jQuery FileDrop - HTML5拖放文件) 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/