7

I'm using Expo and its ImagePicker to grab the image from gallery. It returns both uri and base64.

Now I want to upload the image in a multipart/form-data request.

The problem is that the server only accepts File while below code sends [object Object] instead.

Image of the request

const formData = new FormData();

const data = {
  jwt,
};

formData.append('message', JSON.stringify(data));

formData.append('avatar', {
  uri: avatar,
  type: 'image/png',
  name: 'avatar.png'
});

fetch(url, {
  method: 'POST',
  body: formData,
  headers: {
    Accept: 'application/json',
  },
})

Since I'm using Expo I'm limitted to libraries that it supports. Also adding Content-Type header doesn't work at all and server can't even recognize the message.

Pouria
  • 411
  • 3
  • 10
  • same issue for me . not able to resolve this issue. Does anyone have done this? – Anuj Aug 30 '18 at 10:46
  • same issue here, did you find a solution ? – Sebastien H. Sep 27 '18 at 08:50
  • I'm having the same issue but on React Native CLI. The file is the actual file object up until I append it to the FormDate, at which point it becomes the string `[object Object]` – Ash West Sep 29 '22 at 15:48

2 Answers2

1

If you see that file being sent as [object object] in your request params, that might occur due to two reasons:

  1. The file that you are sending is not a file (or not a file object). A FormData should only receive a File or a Blob object in order to be sent on a request. Note that you have the right keys on your object and that it is indeed a File or a Blob.

  2. As mentioned, it might be the Content-Type header which should not be set

Roysh
  • 1,542
  • 3
  • 16
  • 26
  • In the OP's case, is probable that the URI (`avatar` in `uri: avatar`) is a data URI. In that case, it'd be required to [Convert Data URI to File then append to FormData](https://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata). – salzo Dec 06 '22 at 09:49
0

For React, if you want to upload image and avoid [object object] error, there is a need to setFile for input type handleChange

const file = event.target.files[0]    
setFile({
    picturePreview: URL.createObjectURL(event.target.files[0]),
    pictureAsFile: event.target.files[0]
})

And then calling in formData like:

formData.append('file_attachment', file.pictureAsFile)

Full working example here: https://youtu.be/yTGXNvHQ4BQ

Inderjeet
  • 1
  • 4