1

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

Kartikey
  • 4,516
  • 4
  • 15
  • 40
Rahman Haroon
  • 1,088
  • 2
  • 12
  • 36

3 Answers3

5

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.

Moistbobo
  • 2,342
  • 1
  • 7
  • 16
1

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
});
Himanshu
  • 61
  • 5
  • Yeah my issue was related with the image type `'image/jpg'` is not uploading and when i replaced that with `'image/jpeg'` it worked fine – Rahman Haroon Sep 23 '21 at 07:41
0

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

Rahman Haroon
  • 1,088
  • 2
  • 12
  • 36