2

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 2

1
>.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

Sign up to request clarification or add additional context in comments.

1 Comment

תודה רבה, עזרת לי מאוד. תוכל בבקשה לעזור לי גם מה הטעות שלי בשאלה: stackoverflow.com/questions/67692777/…
1

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?

1 Comment

I do not know. I tried all the options I thought could be and each one gave me another error. Could you perhaps help me know what he expects to receive and that I do not give? If there is any information missing from what I gave, write to me and I will edit the question. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.