Does fetch support multiple file upload natively?

最后都变了- 提交于 2019-11-30 20:30:50

问题


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?


回答1:


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.




回答2:


If you want multiples file, you can use this

var input = document.querySelector('input[type="file"]')

var data = new FormData()
for (const file of input.files) {
  data.append('files',file,file.name)
}

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


来源:https://stackoverflow.com/questions/47738642/does-fetch-support-multiple-file-upload-natively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!