我使用 dropzone.js 作为 Flask 应用程序的一部分,用户可以同时上传多个文件夹。但有时有关文件最有值(value)的信息是文件夹名称。
一个例子可以是:
文件夹A
- 样本.txt
- img.png
文件夹B
- 样本.txt
- img.png
假设它们将整个文件夹拖放到拖放区,是否可以注册哪些文件来自文件夹 A,哪些文件来自文件夹 B?
最佳答案
在 this answer 的帮助下我知道了如何做到这一点以及 MDN 关于 Using FormData objects 的文章.
如果您在模板中像这样定义您的拖放区:
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("form#my-awesome-dropzone",
{ url: "/upload",
});
然后,您必须为 sending
事件添加一个事件处理程序,该事件处理程序接受 file.fullPath
字符串,并将其添加到一个 Blob 中,该 Blob 成为 >multipart/form-data
提交。
myDropzone.on("sending", function(file, xhr, formData) {
// get the original fullPath and add it to the multipart form.
var blob = new Blob([file.fullPath], { type: "text/plain"});
formData.append("originalPath", blob);
});
请注意,这实际上会向您的表单提交添加一个名为 blob
且具有 text/plain
mime 类型的第二个文件。为了可视化这一点,在 Flask 服务器上的上传路由中,您可以 print(request.files)
给出:
ImmutableMultiDict(
[('originalPath', <FileStorage: 'blob' ('text/plain')>),
('file', <FileStorage: 'up.txt' ('text/plain')>)
])
因此,要从服务器端提取实际的字符串,您可以执行以下操作:
original_path = request.files['originalPath'].read().decode('utf-8')
请注意,从前端 Angular 来看,dropzone 不知道相对于被删除的文件或文件夹的父文件夹,因此:
- 将名为
up.txt
的文件拖放到 Dropzone 中,original_path
将为“未定义”
。 - 将一个名为
untitledfolder
的文件夹(其中包含名为up.txt
的文件)拖放到Dropzone中,original_path
将是'untitledfolder/up.txt'
。
您应该在后端构建一些功能来验证传入的信息,并相应地解析这些字符串。
关于javascript - 是否可以使用 dropzone.js 获取文件上传的文件夹名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65990551/