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 是否支持原生多文件上传?
基础教程推荐
- 直接将值设置为滑块 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01