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.

3
  • same issue for me . not able to resolve this issue. Does anyone have done this? Commented Aug 30, 2018 at 10:46
  • same issue here, did you find a solution ? Commented Sep 27, 2018 at 8: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] Commented Sep 29, 2022 at 15:48

2 Answers 2

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

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

1 Comment

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.
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

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.