reactjs - 如何通过 api 在 react 中上传图片?
问题描述
今天看了很多关于如何通过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”。
我尝试修复的任何内容都会导致另一个错误,我真的很茫然。
问候
解决方案
>.append ('groupImage', values.imageFile)
首先,请确保key
您的formdata
对象的名称可以匹配您的模型类属性的名称。
formData.append('imageName', values.imageName);
//...
//it should be imageFile, not groupImage
formData.append('imageFile', values.imageFile);
此外,请将该[FromForm]
属性应用于动作参数,如下所示。
public void Post([FromForm]Group group)
{
//...
测试结果
推荐阅读
- c# - 如何在 Entity Framework 数据库中查询两个日期之间的记录,然后返回该信息以显示在屏幕上
- azure - 需要有关 Azure 中托管磁盘的帮助
- javascript - jqgrid过滤工具栏清除搜索设置错误的默认值
- django - Celery 和 django 不能按预期工作
- reactjs - 如何在 npm 脚本中使用自定义 env(.env.production.abc) 文件
- angular - 如何将运行时有效的功能从组件移动到服务
- python - 将等高线图和线图作为单独的子图返回 - Matplotlib
- javascript - 在 if 语句上使用 Promise
- c# - 调用 API 同步还是异步?
- visual-studio-code - Intellisense 在代码片段中不起作用 - VS Code