提取功能是否支持本机上载多个文件? [英] Does fetch support multiple file upload natively?

查看:98
本文介绍了提取功能是否支持本机上载多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript正确设置我的FormData.

I am trying to set my FormData properly using javascript.

我需要能够上传jpg/png,但将来可能需要使用fetch上传其他一些文件类型pdf/csv.

I need to be able to upload jpg/png, but I might need to upload some other file types pdf/csv in the future using fetch.

我希望它会将数据附加到表单上

I expect it to append the data to the form

此代码段运行正常:

const formData = new FormData(document.querySelector('form'));
formData.append("extraField", "This is some extra data, testing");

return fetch('http://localhost:8080/api/upload/multi', {
    method: 'POST',
    body: formData,
});

const formData = new FormData();
const input = document.querySelector('input[type="file"]');
formData.append('files', input.files);

fetch是否支持本机上传多个文件?

Does fetch support multiple file upload natively?

推荐答案

您的代码存在问题formData.append('files', input.files); 取而代之的是,您应该上传每个循环并使用唯一键的文件,例如

The issue with your code is in the lineformData.append('files', input.files); Instead of that, you should upload each file running a loop with unique keys, like this

const fileList = document.querySelector('input[type="file"]').files;
    for(var i=0;i<fileList.length;i++) {
    formData.append('file'+i, fileList.item(i));    
}

我在您的代码此处中创建了一个简单的错误提琴.您可以在此处查看其提交的帖子数据,在这里可以看到没有文件上传.

I have created a simple error fiddle here with your code. You can check its' submitted post data here, where you can see that no file has been uploaded.

在页面底部,您可以找到

At the bottom of the page you can find

.

我已在修复程序此处进行了更正.您可以从服务器检查其发布数据",其中显示了我上传的两个文件的详细信息.

I have corrected the fiddle here with the fix. You can check its'post data from the server, where it shows the details of the two files that I uploaded.

这篇关于提取功能是否支持本机上载多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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