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

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

问题描述

我有一个正常的< input type =file> 文件上传的网站,当提交表单时将数据发布到后端。 / p>

我想逐步增强表单,以便您可以从浏览器外部的任何地方在浏览器中放置文件(而不仅仅是在文件输入字段中,浏览器)上传它。

表单自动提交是否不重要。因此,如果拖放只选择文件字段中的文件,而不开始上传,那没问题。我不需要支持多个文件。我不需要显示上传进度,缩略图或任何幻想。



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



我想一个渐进的增强,不需要任何后端的变化。它应该使用页面中的表单同步发生。 JS很好,只要上传发生在前台。当然,同步AJAX是行不通的。虽然不是真正的同步(JavaScript执行不会真的停止),但是,您可以通过编程方式设置由< input type =file> 选择的文件。事实上,这样的元素和拖动共享他们的文件后端实现( File FileList 实例)前锋。更重要的是,由于两个前端使用 FileList s,所以拖动多个文件的工作就像一个无缝的工作一样。

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

  $(document).on(dragover drop,function(e){
e.preventDefault(); //允许删除并不导航到文件(drop,function(e){
$(input [type ='file'])
.prop(files,e。 ); //将文件放入元素
.closest(form)
.submit(); // autosubmit以及
});


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.

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.

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.

解决方案

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.

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天全站免登陆