如何一次从React js发送多个文件到后端?

时间:2019-12-24 07:50:38

标签: javascript html reactjs react-native

如何将多个文件或图像发送到后端。 我正在使用React js作为前端部分。

1 个答案:

答案 0 :(得分:0)

let files = // list of files
const formData = new FormData();

for (let i = 0; i < files.length; i++) { 
    formdata.append(`images[${i}]`, {
                    uri: pathOfFile,
                    name: fileName.jpg,
                    type: mimeType(eg. "image/jpeg")
    });
}


//if you are using axios

axios.post('https://mywebsite.com/endpoint/', formData, {
    headers: {
    'content-type': 'multipart/form-data'
    }
}).then(response => {
    console.log(response.data)
});
//if you are using fetch

fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
    'Content-Type': 'multipart/form-data',
},
body: formData,
});