Search code examples
react-nativeaxiosmultipartform-data

How to upload image with axios using form data in react-native


I am trying to upload an image after an image capture in react native using axios and formData. I am using the react-native-camera package to capture the image.

I have checked the other similar answers but none of them are working.

These are the two methods that I tried but it's not working. I am getting Error: Network Error in the below method.

  let bodyFormData = new FormData();
  bodyFormData.append(`q_image_${serial}`, {
    uri: 'file:///data/user/0/com.student/cache/Camera/b6217266-35d5-4a0c-b09e-0c9f12777194.jpg', 
    type: 'image/jpeg',
    name: 'someName',
  });
  
  const { data } = await axios({
    method: 'post',
    url: `${baseURL}/service.php`,
    headers: {
      'Content-Type': 'multipart/form-data' 
    },
    data: bodyFormData
  });

  console.log('UPLOAD', data);

enter image description here

I am getting Images not uploaded response from the server with the below method.

  let bodyFormData = new FormData();
  bodyFormData.append(`q_image_${serial}`, 'file:///data/user/0/com.student/cache/Camera/b6217266-35d5-4a0c-b09e-0c9f12777194.jpg');
  
  const { data } = await axios({
    method: 'post',
    url: `${baseURL}/service.php`,
    headers: {
      'Content-Type': 'multipart/form-data' 
    },
    data: bodyFormData
  });

  console.log('UPLOAD', data);

The server is working fine. I am able to upload an image using postman.

enter image description here

Is this an issue of react-native-camera or formData or axios?

Edit: I found it. I am using react-native version 0.62.* and this is an open issue on github.


Solution

  • I have found the issue and currently this is an open issue of react-native. If anyone is facing the same and is on RN version 0.62.* then please follow the steps.

    1. In gradle.properties change Flipper Version to 0.52.0

      FLIPPER_VERSION=0.52.0
      

    For some reason I got a multi-dex error after this and if you are facing the same then:

    1. In app/build.gradle add

      implementation 'com.android.support:multidex:1.0.3'
      
    2. Add multiDexEnabled true in defaultConfig in app/build.gradle.

      defaultConfig {
         applicationId "com.packageName"
         minSdkVersion rootProject.ext.minSdkVersion
         targetSdkVersion rootProject.ext.targetSdkVersion
         versionCode 1
         versionName "1.0"
         multiDexEnabled true
      }