Axios post formdata not working properly in react native

Viewed 1022

I need to send an image and some details as form-data in react-native

For that, I'm using axios post method.

Here is my code:

const formData = new FormData();

formData.append('taskId', taskId);
formData.append('taskName', taskName);
formData.append('projectId', projectId);
formData.append('projectName', projectName);
formData.append('media', media);

const res = await Axios.post(`${URL}`, formData, {
  headers: {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'multipart/form-data',
  },
});

My server is getting media files as empty.. can anyone know what am I doing wrong here!?

Here is my request header: My request header

PS: I. have tested on postman and its working fine over their

3 Answers

I believe the issue is that you're trying to send media as a json object. There are two ways to solve this.

1. Stringify the media before submitting it

    const formData = new FormData();
    formData.append('media', JSON.stringify(media));

You may also need to make necessary changes to your backend to handle this.

2. Split the media object into separate fields

You mentioned that the media object has a name and file, so you can do something like this.

    const formData = new FormData();
    formData.append('mediaName', media.name);
    formData.append('media', media.file);

Note that in the second example, I am assuming the properties of the media object.

I think for your use case, some variation of the second solution is preferred as it is already working on postman.

In my case the issue was with media type the library I used to choose media was giving media type of image/jpg if I select png or jpg or jpeg. so I upadted my code like this

 mediaData.forEach((item: any, index: number) => {
     formData.append(`media`, {
          uri: item?.uri,
          type: item?.type === 'image/jpg' ? 'image/jpeg' : item?.type,
          name: item?.fileName,
     });
 });

After updating like this everything works fine

When sending Image to Backend you have to Send Type along with image Try this

var formdata = new FormData();
  formdata.append('profile_image', {
    uri: media,
    name: "mediaName",
    type: mimeType
});
Related