Error in uploading Multiple Images in ReactNative

Viewed 78
const availabilityData = new FormData();

  availabilityData.append('name', title);
  availabilityData.append('foodType', foodType);
  availabilityData.append('availability_type', category);
  availabilityData.append('description', description);
  availabilityData.append('total_quantity', quantity);
  availabilityData.append('cooked_time', madeOn);
  availabilityData.append('best_before', bestBefore);
  availabilityData.append('storage_description', storageDesc);
  availabilityData.append('latitude', fromLocation.latitude);
  availabilityData.append('longitude', fromLocation.longitude);
  availabilityData.append('city', selectedCity);
  availabilityData.append('creator_delivery_option', deliveryOption);

  for (let i = 0; i < imageLoc.length; i++) {
    const newFile = {
      uri: imageLoc[i],
      type: 'image/jpg',
      name: new Date(),
    };
    availabilityData.append('files[]', newFile);
  }

  await axios({
    url: constants.BASE_URL + 'availability/createAvailability',
    method: 'post',
    data: availabilityData,
    headers: {
      Authorization: `UserData ${token}`,
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },

  })
    .then(function (response) {
      Alert.alert('Availability Created Successfully');
      navigation.popToTop();
      removeAllInputs();
      setLoading(false);
    })
    .catch(function (error) {
      console.log(error);
      setLoading(false);
    });
}

imageLoc is the State where I have stored the location of selected Images.

output when I print imageLoc: ["content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-151358739.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-151913720.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-15253326.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-152139570.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-1524187.jpg"]

Error I got in the backend

1 Answers

You are having Content-Provider paths in your file array. A content provider is not a valid url in Android and probably Axios is not prepared to handle them. In this case you can copy the files for example with react-native-fs to a different location:

RNFS.copyFile(uri, targetPath)

And then provide the targetPath to axios. Make sure to delete the copies after sending the images.

Related