简体   繁体   English

拖放文件上传

[英]Drag and Drop file upload

I have an HTML form, used to upload a file. 我有一个HTML表单,用于上传文件。 The file is added to the hidden file input field. 该文件将添加到隐藏文件输入字段。 When the form is submitted, this file and any other params are sent to the server. 提交表单后,此文件和任何其他参数将发送到服务器。

The app uses jQuery. 该应用程序使用jQuery。

var data = ev.clipboardData.files;
$(ev.target).closest(".upload-box").find("input[type=file]").prop("files", data);

I have read several approaches, but none of them used the input[type=file] field. 我已经阅读了几种方法,但是没有一种方法使用input [type = file]字段。

How does one store the dropped file, if it's not by using the input field? 如果不使用输入字段,如何存储删除的文件?

I also tried to implement this: 我也尝试实现这一点:

https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop

I tried to add something like 我试图添加类似

$(ev.target).closest(".upload-box").find("input[type=file]").prop("files", files);

which throws 哪个抛出

TypeError: Failed to set the 'files' property on 'HTMLInputElement': The provided value is not of type 'FileList'.

So it looks like "files"/FileList becomes read-only? 因此,看起来“文件” / FileList变为只读?

Please point me in the right direction. 请指出正确的方向。

You need to look into javascripts filereader api . 您需要研究javascripts filereader api The contents of an input type file are always readonly, however what you can do is read those contents, and store them in a global array (If you want to post multiple files). 输入类型文件的内容始终为只读,但是您可以读取这些内容,并将其存储在全局数组中(如果要发布多个文件)。

Once they're in an array you can do what you want with them, eg validate file type, size, etc... 将它们放入数组后,您可以对它们执行所需的操作,例如,验证文件类型,大小等。

We had to change clipboardData to dataTransfer 我们不得不将剪贴板数据更改为dataTransfer

- var data = ev.clipboardData.files;
+ var data = ev.dataTransfer.files;

$(ev.target).closest(".upload-box").find("input[type=file]").prop("files", data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM