skip to Main Content

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.

  1. 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}`,
           });
         }
       };
     };
    
    1. 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));
      };
      
    2. 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 });
      };
  1. 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


  1. Chosen as BEST ANSWER

    Found a solution by using fetch instead of axios on my api call


  2. 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:

    import * as FileSystem from 'expo-file-system';
    const imageUploading = async () => {
        const data = await FileSystem.uploadAsync(
          URL,
          image, // uri of the image 
          {
            httpMethod: 'POST',
            uploadType: FileSystem.FileSystemUploadType.MULTIPART,
            fieldName: 'file',
          },
        );
    };
    
    Login or Signup to reply.
  3. Sending the whole image object works fine:

    const createRequestCall = async () => {
      const formData = new FormData();
      formData.append('file', pickedImage);
      ...
    
      dispatch(uploadPhoto(formData));
    };
    

    I use this type:

    interface ImageType {
      uri: string;
      name: string;
      type: string;
    }
    

    Appending that object works fine even though Typescript gives an error.
    FormData.append expects a string | Blob, but I have yet to figure out how to supply my custom Image type without errors.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search