I am using expo-image-picker for UI interface to upload images to my app. I am finding some diffuculties when I want to upload the images to backend. The images are not uploaded and I don’t get the reason. I have tried everything but nothing seems to work.
-
How I set the data to the image state
const showImagePicker = async () => { Promise.all([ImagePicker.requestMediaLibraryPermissionsAsync(), ImagePicker.requestCameraPermissionsAsync()]).then(result => { result.forEach(permission => { return !permission.granted; }); }); const result: ImagePicker.ImageInfo = (await ImagePicker.launchImageLibraryAsync({ base64: true, })) as ImagePicker.ImageInfo; const uriParts = result.uri.split('.'); const fileType = uriParts[uriParts.length - 1]; if (!result.cancelled) { setPickedImagePath({ uri: Platform.OS === 'android' ? result.uri : result.uri.replace('file://', ''), name: `photo.${fileType}`, type: `application/${fileType}`, }); } }; };
-
How I append the data to formData
const createRequestCall = async () => { const formData = new FormData(); formData.append('file', pickedImage.uri); formData.append('data2', 'test'); formData.append('data3', '123'); formData.append('data4', 'test'); dispatch(uploadPhoto(formData)); };
-
How I dispatch the request if file is loading.
-
export const uploadPhoto=
(photoRequest: FormData) =>
async (dispatch: Dispatch<Action>): Promise<void> => {
dispatch({ type: ActionTypes.API_LOADING, payload: apiIsLoading });
const response = await Apis.requestPhoto(fileRequest);
dispatch({ type: ActionTypes.API_LOADING, payload: apiIsNotLoading });
};
- The request I send to the backend.
async requestPhoto(data: FormData): Promise<IDetails> {
const response = await http.post<IDetails, AxiosResponse<ITripDetailsResponse>>(${baseURL}/upload/image, data, {
headers: { 'Content-Type': 'multipart/form-data' },
transformRequest(formData, headers) {
return data;
},
});
return response.data;
},
3
Answers
Found a solution by using fetch instead of axios on my api call
I think, that is impossible to send image using
axios
because of the platform.But, the good news is that
Expo
already has expo-file-system package.Using it you can upload your image to backend.
Example:
Sending the whole image object works fine:
I use this type:
Appending that object works fine even though Typescript gives an error.
FormData.append
expects astring | Blob
, but I have yet to figure out how to supply my custom Image type without errors.