fetch 是否支持原生多文件上传?

Does fetch support multiple file upload natively?(fetch 是否支持原生多文件上传?)

本文介绍了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 是否支持原生多文件上传?

基础教程推荐