【问题标题】:File drag and drop event in jqueryjquery中的文件拖放事件
【发布时间】:2011-09-30 01:59:40
【问题描述】:

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

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

我应该在 jquery(或类似的东西)中寻找一个事件吗?

非常感谢任何帮助!

【问题讨论】:

标签: javascript jquery ajax upload


【解决方案1】:

我在研究一些 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]);

 }

现在您可以发送 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);

【讨论】:

  • 我发现只听“drop”不会在 Chrome 中捕获文件,它只会在我在给定元素上同时听“dragover”和“drop”并执行 .stopPropagation( ) & .preventDefault() 两个事件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
相关资源
最近更新 更多