【发布时间】:2021-02-14 09:44:35
【问题描述】:
我正在尝试在对象内使用 Axios 上传图像。我可以使用new FormData() 获取文件并将其放入对象中,但提交图像为空。如何结合其他 JSON 数据上传对象中的文件?
import React, { useState } from 'react';
import axios from 'axios';
function UploadFiles() {
const [submitFile, setSubmitFile] = useState({});
const handleChange = e => {
setSubmitFile(e.target.files[0]);
};
const handleSubmit = () => {
const formData = new FormData();
formData.append('document', submitFile);
formData.append('Answer_name', 'image');
formData.append('Document', true);
formData.append('Answer', 'Got some data');
console.log(submitData) // I get formData data
const submitData = {
UUID_Formulier: '117F994F-F803-7249-91E9-EE1E7B691DFF',
answers: [formData], // this will be an empty object on calling axios.post
};
axios
.post('/submit', submitData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(() => {
console.log('success');
})
.catch(() => {
console.log('failed error');
});
};
return (
<div>
<input type="file" name="image" onChange={handleChange} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
图片必须放在 answers 数组中。当我将 FormData 放入 answers 数组时,它是一个空对象。如何将文件 formData 放入 JSON 对象或数组然后全部提交?
【问题讨论】:
标签: javascript reactjs file-upload axios multipartform-data