I’m trying to send a multipart/form-data request to the Google Drive API from my React Native app.
When I use Postman, the request works perfectly, but when I try to implement the same request in React Native using fetch or axios, I keep getting a “Malformed multipart body” error.
I’m constructing the request using FormData, adding metadata (metadata) and the file (file).
This setup works fine in Postman, so I suspect there’s something different in how React Native handles FormData or the Content-Type header for multipart requests.
Has anyone experienced this issue in React Native?
Is there a specific way to configure FormData to behave the same way as it does in Postman?
Or, if you have any recommendations for alternative approaches to send multipart/form-data requests from React Native, I’d really appreciate the guidance.
Thanks in advance for any help!
export const uploadToGoogleDrive = async (data) => {
try {
const accessToken = await signInWithGoogle();
const fileName = data.title;
const fileDescription = data.description;
const file = data.file;
const fileMimeType = file.assets[0].mimeType;
const formData = new FormData();
formData.append("metadata", JSON.stringify({
name: fileName,
mimeType: fileMimeType,
description: fileDescription,
parents: [GOOGLE_DRIVE_FOLDER_ID]
}), { type: 'application/json' });
formData.append('file', {
uri: file.assets[0].uri,
type: fileMimeType,
name: fileName,
});
const response = await fetch(`${GOOGLE_DRIVE_ENDPOINT}/files?uploadType=multipart`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
},
body: formData,
});
if (!response.ok) {
const errorText = await response.json();
console.log("Detailed Error:", errorText);
throw new Error(`Error uploading file: ${response.statusText}, details: ${errorText}`);
}
return response;
} catch (error) {
console.error("Upload error:", error);
if (error.response) {
console.error("Response data:", error.response.data);
} else if (error.request) {
console.error("Request details:", error.request);
} else {
console.error("Error:", error.message);
}
}
};