【发布时间】:2019-10-09 11:20:47
【问题描述】:
下面的代码我在 reactJS 中向媒体数组添加对象
const formData = new FormData()
formData.append('file', file, file.name)
const obj = {
'id': id,
'type': 'doc',
'data': formData,
url: file
};
setID(id + 1);
setMedia([...media, obj]);
现在我通过 axios 将它发送到 api
function addNew() {
setProgressing(true)
axios.post(uri + '/api/add', {
map_id: props.data.id,
questions: JSON.stringify(media)
})
.then(res => {
props.updateStep();
})
.catch(err => {
});
}
但是在服务器端我收到如下数组的对象 查看数据,url为空
{id: 1, type: "image", data: {{}}, url: {}}
这是请求头
每次上传图片时调用的SetMedia代码
function handleUploadChange(e) {
handleClose();
const file = e.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = () => {
const formData = new FormData()
formData.append('file', file, file.name)
const obj = { 'id': id, 'type': 'image', 'data': formData, url: file };
setID(id+1);
setMedia([...media, obj]);
}
reader.onerror = function () {
console.log("error on load image");
};
}
【问题讨论】:
-
我用代码解释我的问题
-
您的 formData 和文件是空的,这就是它没有被传递的原因。您必须检查它们为什么是空的。
-
如果我对媒体数组执行
JSON.stringify(),它们将变为空 -
您将不得不透露更多代码
-
@EugeneSunic 我想要的是将图像存储在对象数组中,然后将该数组发送到 Api
标签: javascript php reactjs laravel axios