Reactjs 如何通过api在react中上传图像?
今天我看到了一些关于如何通过api在react中上传照片的教程 我做了所有的事,尝试了所有的方法。但最后我被卡住了 (在整个解释过程中,我将只关注图像上传的功能) 在模型中,我有组和变量-Reactjs 如何通过api在react中上传图像?,reactjs,asp.net-core,Reactjs,Asp.net Core,今天我看到了一些关于如何通过api在react中上传照片的教程 我做了所有的事,尝试了所有的方法。但最后我被卡住了 (在整个解释过程中,我将只关注图像上传的功能) 在模型中,我有组和变量- [NotMapped] public IFormFile ImageFile {get; set; } 在api中,我得到 [Route ("Add")] [HttpPost] public void Post (Gro
[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更改为
常量obj={'groupImage':values.imageFile
}
我收到一条错误消息400-
“无法将JSON值转换为System.String.Path:$.groupImage
如果我从state发送值
axios.post('api/groups/add',值)
我收到一条错误消息System.NotSupportedException:不支持反序列化接口类型。键入“Microsoft.AspNetCore.Http.ifformFile”。路径:$.imageFile |行号:0 | BytePositionLine:6939781。
--->System.NotSupportedException:不支持接口类型的反序列化。请键入“Microsoft.AspNetCore.Http.ifformfile”
我试图修复的任何东西都会导致另一个错误,我真的不知所措
关于通常415表示您没有设置正确的内容类型标题。您尝试上载的API是否提到它期望的可接受类型或编码
>.append ('groupImage', values.imageFile)
首先,请确保formdata
对象的键
与模型类属性的名称匹配
formData.append('imageName', values.imageName);
//...
//it should be imageFile, not groupImage
formData.append('imageFile', values.imageFile);
此外,请将[FromForm]
属性应用于操作参数,如下所示
public void Post([FromForm]Group group)
{
//...
测试结果
我不知道。我尝试了所有我认为可能的选项,但每个选项都给了我另一个错误。你能帮我知道他希望得到什么,而我没有提供什么吗?如果我提供的内容中缺少任何信息,请写信给我,我会编辑这个问题。谢谢你לעזור לי גם מה הטעות שלי בשאלה:
public void Post([FromForm]Group group)
{
//...