【发布时间】:2021-06-04 15:57:46
【问题描述】:
今天看了很多关于如何通过api在react中上传照片的教程。
我做了一切,尝试了所有方法。但最后我卡住了。
(在整个解释中,我将只关注图像上传的功能) 在模型中,我有组和变量 -
[NotMapped]
public IFormFile ImageFile {get; set; }
在 api 我得到
[Route ("Add")]
[HttpPost]
public void Post (Group group)
我在状态-
const initialFieldValues = {
GroupName: '',
GroupAbout: '',
imageName: '',
imageSrc: defaultImageSrc,
imageFile: null
}
const [values, setValues] = useState (initialFieldValues)
当改变图像有一个功能-
const handleImg = (e) => {
if (e.target.files && e.target.files [0]) {
let imageFile = e.target.files [0];
const reader = new FileReader ();
reader.onload = x => {
setValues ({
... values,
imageFile,
imageSrc: x.target.result
})
}
reader.readAsDataURL (imageFile)
SetDisplayImg ("block");
}
else {
setValues ({
... values,
imageFile: null,
imageSrc: defaultImageSrc
})
}
};
以及提交表单时
const handleFormSubmit = e => {
e.preventDefault ()
const formData = new FormData ()
.append ('groupImage', values.imageFile)
addOrEdit (formData)
}
const addOrEdit = (formData) => {
axios.post ('api / groups / add', formData) .catch (error => {
console.log (error.response.data);
console.log (error.response.status);
console.log (error.response.headers);
});
}
在此代码中 - 导致 错误 415 (即使上传图像,但即使我只将其他变量放入字符串并正常工作。)
如果我在 api 中添加 [FromForm],它不会响应我,即它不会给我写错误消息,也不会到达 api(我检查调试)
如果我将 axios 更改为 const obj = {'groupImage': values.imageFile }
axios.post ('api / groups / add', obj) .catch (error =>
我收到一条错误消息 400- "JSON 值无法转换为 System.String。路径:$ .groupImage
如果我从状态发送值 axios.post('api/groups/add', values)
我收到一条错误消息System.NotSupportedException:不支持接口类型的反序列化。键入“Microsoft.AspNetCore.Http.IFormFile”。路径:$ .imageFile |行号:0 | BytePositionInLine:6939781。 ---> System.NotSupportedException:不支持接口类型的反序列化。键入“Microsoft.AspNetCore.Http.IFormFile”。
我试图修复的任何东西都会导致另一个错误,我真的很茫然。
问候
【问题讨论】:
标签: reactjs asp.net-core