Reputation: 431
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.
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.
Upvotes: 7
Views: 1590
Reputation: 1550
If you see that file being sent as [object object]
in your request params, that might occur due to two reasons:
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.
As mentioned, it might be the Content-Type
header which should not be set
Upvotes: 1
Reputation: 1
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
Upvotes: 0