首页 > 解决方案 > 如何通过 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”。

我尝试修复的任何内容都会导致另一个错误,我真的很茫然。

问候

标签: reactjsasp.net-core

解决方案


>.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)
{
    //...

测试结果

在此处输入图像描述


推荐阅读