How to upload images in react via api?

Viewed 104

Today I saw a number of tutorials on how to upload photos in react via the api.

I did everything, tried all the methods. But in the end I get stuck.

(During the whole explanation I will focus only on the features of the image upload) In Models I have groups and variable -

        [NotMapped]
        public IFormFile ImageFile {get; set; }

In api I get

  [Route ("Add")]
        [HttpPost]
        public void Post (Group group)

And I have in state-

  const initialFieldValues ​​= {
        GroupName: '',
        GroupAbout: '',
        imageName: '',
        imageSrc: defaultImageSrc,
        imageFile: null
    }
    const [values, setValues] = useState (initialFieldValues)

When changing the image has a function-

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
            })
        }

    };

And when submitting the form


    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);
        });
        
    }

In this code -makes error 415 (even regardless of uploading the image but, even if I put it only other variables that get stringed and work normally.)

If I add [FromForm] in the api it does not respond to me, i.e. it does not write me an error message nor does it reach the api (I checked in debugging)

If I change the axios to const obj = {'groupImage': values.imageFile }

    axios.post ('api / groups / add', obj) .catch (error =>

I get an error message 400- "The JSON value could not be converted to System.String. Path: $ .groupImage

And if I send the value from state axios.post ('api / groups / add', values)

I get an error message System.NotSupportedException: Deserialization of interface types is not supported. Type 'Microsoft.AspNetCore.Http.IFormFile'. Path: $ .imageFile | LineNumber: 0 | BytePositionInLine: 6939781. ---> System.NotSupportedException: Deserialization of interface types is not supported. Type 'Microsoft.AspNetCore.Http.IFormFile'.

Anything I try to fix, it causes another error, I'm really at a loss.

Regards

2 Answers

Usually a 415 means you aren't setting the right Content-Type header. Does the API you are trying to upload to mention acceptable types or encodings it expects?

>.append ('groupImage', values.imageFile)

Firstly, please make sure the key of your formdata object can match your model class property's name.

formData.append('imageName', values.imageName);
//...

//it should be imageFile, not groupImage
formData.append('imageFile', values.imageFile);

Besides, please apply the [FromForm] attribute to action parameter, like below.

public void Post([FromForm]Group group)
{
    //...

Test Result

enter image description here

Related