Does fetch support multiple file upload natively?(fetch 是否支持原生多文件上传?)
问题描述
总结
我正在尝试使用 javascript 正确设置我的 FormData
.
我需要能够上传 jpg/png
,但我以后可能需要使用 fetch 上传一些其他文件类型 pdf/csv
.
预期
我希望它将数据附加到表单中
错误
工作
这段代码运行良好:
const formData = new FormData(document.querySelector('form'));formData.append("extraField", "这是一些额外的数据,正在测试");return fetch('http://localhost:8080/api/upload/multi', {方法:'POST',正文:formData,});
不工作
const formData = new FormData();常量输入 = document.querySelector('input[type="file"]');formData.append('files', input.files);
问题
fetch
是否原生支持多文件上传?
你的代码问题出在formData.append('files', input.files);
取而代之的是,您应该上传每个运行带有唯一键的循环的文件,像这样
const fileList = document.querySelector('input[type="file"]').files;for(var i=0;i
我用您的代码创建了一个简单的错误小提琴.
我已在
Summary
I am trying to set my FormData
properly using javascript.
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.
Expected
I expect it to append the data to the form
Error
Working
This snippet is working fine:
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,
});
Not working
const formData = new FormData();
const input = document.querySelector('input[type="file"]');
formData.append('files', input.files);
Question
Does fetch
support multiple file upload natively?
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.
这篇关于fetch 是否支持原生多文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:fetch 是否支持原生多文件上传?


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01