Reputation: 1266
In my React Native project i'm using react-native-image-picker
for image upload. Here, i am using formData to upload image. Image URL is there, but when i console the formData it shows {}. I don't know why this is happening. Here's the code :
uploadImageAsync = async (imgUri, token) => {
let apiUrl = 'url';
let formData = new FormData();
let uriParts = imgUri.split('.');
let fileType = uriParts[uriParts.length - 1];
//generate some random number for the filename
var randNumber1 = Math.floor(Math.random() * 100);
var randNumber2 = Math.floor(Math.random() * 100);
formData.append('image', {
uri: imgUri,
name: `photo-${randNumber1}-${randNumber2}.${fileType}`,
type: `image/${fileType}`,
});
console.log('formData :', formData);
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + token,
'Content-Type': 'multipart/form-data',
'Cache-Control': 'no-cache',
},
};
const response = await fetch(apiUrl, options);
const json = await response.json();
}
};
Console of formData shows no data but imgUri
consists image path. Why formData is showing no data?
Upvotes: 3
Views: 1536
Reputation: 17217
The value
property of FormData.append() can be either a USVString
or a Blob
.
Therefore, you can try stringifying your object and then optionally parse the string data.
const imageData = {
uri: imgUri,
name: `photo-${randNumber1}-${randNumber2}.${fileType}`,
type: `image/${fileType}`,
};
const formData = new FormData();
formData.append("image", JSON.stringify(imageData));
const formImageData = formData.get("image");
const parsedFormImageData = JSON.parse(formImageData);
console.log(parsedFormImageData );
Upvotes: 1