0

I'm trying to upload files to the back-end. but it fails

Basically I want to upload 11 images at the same time.

At first I do this

    const title, image1, image2, ... = this.state;
    axios.post(`myapi`, {title, image1, image2})

Here is my state of image 1:

enter image description here

It returns an error of 422 "the given data was invalid"; "image_1": The image field is required.

After several reads online, I found out that to upload and image, you have to use formData. So I tried doing this

const title = this.state.title;

const formData = new FormData();
formData.append('image_1', this.state.image_1);
formData.append('image_2', this.state.image_2);
...
axios.post(`myapi`, {title, formData})

I still get the same 422 error,

enter image description here

tried to console.log the formData

for (var fd of formData) {
  console.log(fd);
}

the results indicate the formData has been appended well. But somehow i could not upload it because it is "invalid data"

enter image description here

Thanks for the help!

2
  • researchhubs.com/post/computing/javascript/… hope this can help you Commented Jun 10, 2019 at 13:34
  • @HardikChaudhary thanks for the reply! I tried adding the filename in the append, and it still does not work. Commented Jun 10, 2019 at 13:51

2 Answers 2

2

You are converting the images to FormData but sending them as JSON. You should include title in formData as well.

const formData = new FormData();
formData.append('title', this.state.title);
formData.append('image_1', this.state.image_1);
formData.append('image_2', this.state.image_2);

And send the data with header as multipart/form-data

axios.post(`https://api.cashless.vip/api/homepage`, formData, {headers: {"Content-type": "multipart/form-data"}});

Hope this works.

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

Comments

0

add the header {"Content-type": "multipart/form-data"}

Comments

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.