I’m using React Native with Expo and I’m trying to upload a images using formData with post and ‘expo-image-picker’. WHen I try to upload a image I get [Error: Unsupported FormDataPart implementation], I don’t understand the iussue, is anyone could help me ?
here’s the code:
const requestPermissions = async () => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
Alert.alert('Permissions Required', 'We need permission to access your photo library.', [
{ text: 'OK' },
]);
return false;
}
return true;
};
const onUploadImage = async asset => {
console.log('file', asset);
const fileToUpload = {
uri: asset.uri,
name: asset.fileName ?? `image_${Date.now()}.jpg`,
type: asset.mimeType ?? 'image/jpeg',
};
const formData = new FormData();
formData.append('file', fileToUpload);
try {
setIsLoading(true);
const response = await postAuthenticatedAPI({
token: user?.access_token,
isChatEndpoint: false,
formData: true,
endpoint: UPLOAD_FILE,
payload: formData,
});
console.log('res', response);
if (response) {
setImageData(prev => ({
...prev,
id: `img_${Date.now()}`,
url: asset.uri,
}));
onImageChange('cover_image', response?.file || asset.uri);
}
} catch (error) {
setModalConfig({
title: 'Error',
subtitle: error?.message || 'Error fetch',
type: 'error',
});
setShowModal(true);
} finally {
setIsLoading(false);
}
};
const showImageOptions = () => {
if (isLoading) return;
Alert.alert('Select Image', 'Choose where you want to select the image from', [
{
text: 'Gallery',
onPress: pickImageFromGallery,
},
{
text: 'Camera',
onPress: takePhoto,
},
{
text: 'Cancel',
style: 'cancel',
},
]);
};
const pickImageFromGallery = async () => {
const hasPermission = await requestPermissions();
if (!hasPermission) return;
try {
const image = await ImagePicker.launchImageLibraryAsync({
mediaTypes: 'images',
allowsEditing: true,
aspect: [1, 1],
quality: 0.8,
});
if (!image.canceled && image.assets && image.assets.length > 0) {
const asset = image.assets[0];
await onUploadImage(asset);
}
} catch (error) {
Alert.alert('Errore', error);
}
};
const takePhoto = async () => {
const { status } = await ImagePicker.requestCameraPermissionsAsync();
if (status !== 'granted') {
Alert.alert('Permissions Required', 'We need permission to access your camera.', [
{ text: 'OK' },
]);
return;
}
try {
const image = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [1, 1],
quality: 0.8,
});
if (!image.canceled && image.assets && image.assets.length > 0) {
const asset = image.assets[0];
await onUploadImage(asset);
}
} catch (error) {
Alert.alert('Errore', error);
}
};
here’s my post function:
export const postAuthenticatedAPI = async ({
payload,
endpoint,
token,
formData = false,
isChatEndpoint = false,
}) => {
const baseUrl = isChatEndpoint
? process.env.EXPO_PUBLIC_BASE_CHAT
: process.env.EXPO_PUBLIC_BASE_URL;
const url = baseUrl + endpoint;
try {
const headersWithFormData = {
Authorization: `Bearer ${token}`,
};
const withoutFormDataHeader = {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
};
const response = await fetch(url, {
method: 'POST',
headers: formData ? headersWithFormData : withoutFormDataHeader,
body: formData ? payload : JSON.stringify(payload),
});
if (response.status === 200 || response.status === 201) {
return await response.json();
} else throw new Error('Server error');
} catch (e) {
const error = new Error(e?.message || 'Something went wrong');
error.info = e.info || null;
error.status = e.status || null;
throw error;
}
};
Where am I wrong ?