拖放文件上传没有AJAX,在前台同步? [英] Drag-and-drop file uploading without AJAX, synchronously in the foreground?

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

问题描述

我有一个网站,有一个常规的 <input type="file"> 文件上传,在提交表单时将数据发布到后端.

I have a web site with a regular <input type="file"> file upload, POSTing the data to the backend when the form is submitted.

我想逐步增强表单,以便您可以将文件从浏览器外部的视口中的任何位置(不仅仅是在某些浏览器中内置的文件输入字段上)拖放以上传.

I would like to progressively enhance the form so that you can drop a file from outside the browser anywhere in the viewport (not just on the file input field, as built into some browsers) to upload it.

表单是否自动提交并不重要.因此,如果拖放仅选择文件字段中的文件,而不开始上传,那也没关系.我不需要支持多个文件.我不需要显示上传进度、缩略图或任何花哨的东西.

Whether or not the form autosubmits isn't important. So if the drag-and-drop only selects the file in the file field, without starting an upload, that's fine. I don't need support for multiple files. I don't need to show upload progress, thumbnails or anything fancy.

我知道有支持拖放上传的 JS 库,但它们似乎都是通过 AJAX 上传的.我可以做到这一点,但随后我需要修改后端和前端以处理上传错误、重定向并在成功时显示正确的消息等等.

I know there are JS libs that support drag-and-drop uploads, but they all seem to upload via AJAX. I could do that, but then I would need to modify the backend and frontend to handle upload errors, redirect and show the right messages on success and so on.

我想要一个不需要任何后端更改的渐进式增强.它应该使用页面中的表单同步发生.JS 很好,只要上传发生在前台".当然,同步 AJAX 是行不通的.

I want a progressive enhancement that doesn't require any backend changes. It should happen synchronously using the form in the page. JS is fine, as long as the upload happens "in the foreground". Synchronous AJAX would not work, of course.

推荐答案

虽然不是真正的同步"(JavaScript 执行实际上不会停止),但您可以设置<input type="file"> 以编程方式.事实上,这些元素和拖动共享它们的文件后端实现(FileFileList 实例),所以它真的很简单.此外,由于两个前端都使用 FileLists,因此可以无缝地拖动多个文件.

Although not really "synchronous" (JavaScript execution won't actually halt), you can set the files selected by <input type="file"> programatically. In fact, such elements and dragging share their file backend implementation (File and FileList instances), so it's really straight-forward. What's more, due to both frontends using FileLists, dragging multiple files work just as seamlessly.

这适用于 Chrome(使用 jQuery):http://jsfiddle.net/qMmPr/.

This works in Chrome (using jQuery): http://jsfiddle.net/qMmPr/.

$(document).on("dragover drop", function(e) {
    e.preventDefault();  // allow dropping and don't navigate to file on drop
}).on("drop", function(e) {
    $("input[type='file']")
        .prop("files", e.originalEvent.dataTransfer.files)  // put files into element
        .closest("form")
          .submit();  // autosubmit as well
});

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

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