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!

wlsonf
  • 31
  • 1
  • 6

2 Answers2

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.

Ashish
  • 986
  • 6
  • 17
0

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