Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

javascript - Does fetch support multiple file upload natively?

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

image

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,
});

image

Not working

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

image

Question

Does fetch support multiple file upload natively?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here.

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.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...