拖放文件上传 [英] Drag and Drop File Uploading

查看:91
本文介绍了拖放文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用< input type =file/> html标记在我的网络应用程序中使用文件上传。我的功能适用于从文件选择器中选择文件并提交文件,但是现在我想在拖放事件上传文件,即用户从他的计算机上的某个位置拖动文件,当他将其丢弃到特定的位置时在我的网页中,该文件开始上传。

I am using file uploading in my web application by using the <input type="file" /> html tag. My feature works well with choosing a file from the file chooser and submitting the file, however now I want to upload a file on drag and drop events i.e. the user drags a file from some location on his computer and when he drops it in a particular section in my web page, the file starts uploading.

到目前为止,我设法通过放弃事件读取文件

Until now I managed to read the files from the drop event by

  function drop(evt)
    {
       evt.stopPropogation();
           evt.preventDefault();

       if (containsFiles(evt))
       {
        var files = evt.dataTransfer.files;
        var count = files.length;

        // Only call the handler if 1 or more files was dropped.
        if (count > 0)
            // upload files
        }
      }
    }

但我如何上传这些文件?出于安全原因,我无法更改input type = file的值。那么我该怎样做才能将这些文件传递给我的servlet?

but how can I upload these files? I can't change the value of input type = file for security reasons. So what can I do to pass these files to my servlet?

推荐答案

你必须使用 FormData (小心IE支持)。

You have to use FormData (beware of IE support).

当发生丢弃时,您需要创建 FormData 对象,并将数据附加到其中,然后将 POST 形成到您的网址。它是异步方法,不会重新加载您的页面。

When drop happens you need to create FormData object, and append data into it, then POST that form to your url. It is asynchronous method and will not reload your page.

function drop(evt) {
  evt.stopPropogation();
  evt.preventDefault();

  var files = evt.dataTransfer.files;
  if (files.length > 0) {
    var form = new FormData();

    for(var i = 0; i < files.length; ++i) {
      var file = evt.dataTransfer.files[i];
      form.append('image_' + i, file, file.name);
    }

    var req = new XMLHttpRequest();
    req.open('POST', '/pathToPostData', true);
    req.onload = function(evt) {
      console.log(req.responseText);
    }
    req.send(form);
  }
}

小心我只在Chrome和Firefox中测试过,IE9可能无法正常工作,但IE10应该如果你测试它,请告诉我们。

Beware that I've tested it only in Chrome and Firefox, IE9 probably will not work but IE10 should, if you test it, let us know please.

这篇关于拖放文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆