10
votes

I am making a POST request to server to upload an image and sending formdata using axios in react-native. i am getting "Network Error". i also try fetch but nothing work.using react native image picker libeary for select image.in postman api working fine

        formData.append('title', Title);
        formData.append('class_id', selectClass._id)
        formData.append('subject_id', checkSelected)
        formData.append('teacher_id', userId)
        formData.append('description', lecture);
        formData.append('type', 'image');

       var arr=[];
       arr.push(imageSource)
       arr.map((file,index)=>{
       formData.append('file',{
       uri:file.path,
       type:file.type,
       name:file.name
       })
       })


       axios({
       method: 'post',
       url: URL + 'admin/assignment/create',
       data: data,
       headers: {
       "content-type": "multipart/form-data",
       'x-auth-token': token,
        },
       })
     .then(function (response) {
    //handle success
    console.log('axios assigment post',response);
      })
   .catch(function (response) {
     //handle error
      console.log('axios assigment post',response);
    });
9
Here is an easy way to upload images or videos with axios stackoverflow.com/a/67987558/13789135 - Irfan wani

9 Answers

10
votes

Project keeps flipper java file under app > source > debug in react native > 0.62. There is an issue with Flipper Network that causes the problem in your case. If you remove the debug folder, you will not be able to debug Android with Flipper, so the best solution is upgrading Flipper version in android > gradle.properties to 0.46.0 that fixes the problem.

You can change it with this line FLIPPER_VERSION=0.46.0

6
votes

I faced the same issue. The following steps worked for me.

  1. update FLIPPER_VERSION=0.52.0 latest
  2. for formData code as below:
let formData = new FormData();
let file = {
          uri: brand.uri, 
          type: 'multipart/form-data', 
          name: brand.uri
};
formdata.append('logo', file);

The type must be 'multipart/form-data' as the post header.

4
votes

REACT NATIVE SOLUTION

If you are using Axios or Fetch in React Native and you got Network Error when uploading the file or data.

Try to commenting below line from the /android/app/src/main/java/com/{your_project}/MainApplication.java

its located around the 40-50 line

initializeFlipper(this, getReactNativeHost().getReactInstanceManager())

https://github.com/facebook/react-native/issues/28551

2
votes

The issue that I was facing which is close to what you are mentioning is that I was getting NetworkError when using image-picker and trying to upload the file using axios. It was working perfectly in iOS but not working in android.

This is how I solved the issue.

There are two independent issues at action here. Let’s say we get imageUri from image-picker, then we would use these following lines of code to upload from the frontend.

const formData = new FormData();
formData.append('image', {
 uri : imageUri,
 type: "image",
 name: imageUri.split("/").pop()
});

The first issue is with the imageUri itself. If let’s say photo path is /user/.../path/to/file.jpg. Then file picker in android would give imageUri value as file:/user/.../path/to/file.jpg whereas file picker in iOS would give imageUri value as file:///user/.../path/to/file.jpg.

The solution for the first issue is to use file:// instead of file: in the formData in android.

The second issue is that we are not using proper mime-type. It is working fine on iOS but not on Android. What makes this worse is that the file-picker package gives the type of the file as “image” and it does not give proper mime-type.

The solution is to use proper mime-type in the formData in the field type. Ex: mime-type for .jpg file would be image/jpeg and for .png file would be image/png. We do not have to do this manually. Instead, you can use a very famous npm package called mime.

The final working solution is:

import mime from "mime";

const newImageUri =  "file:///" + imageUri.split("file:/").join("");

const formData = new FormData();
formData.append('image', {
 uri : newImageUri,
 type: mime.getType(newImageUri),
 name: newImageUri.split("/").pop()
});

I hope this helps to solve your problem :)

1
votes

"react-native": "0.62.1", "react": "16.11.0", "axios": "^0.19.2",

weird solution i have to delete debug folder in android ->app->source->debug

and restart the app again its solve my problem. i think it's cache problem.

1
votes

I had this problem and solve it via commenting the 43 line in android/src/debug/.../.../ReactNativeFlipper.java

// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

could you test it?

0
votes

I recently updated my Flipper to a newer version and it works fine.

The version is defined in the gradle.properties file

# Version of flipper SDK to use with React Native
FLIPPER_VERSION=0.83.0 

Make sure to clean the project in the android folder after changing the flipper version.

./gradlew clean

The solution proposed by @Mahmonir Bakhtiyari is a workaround if you can't update your flipper version, since the network debugger in Flipper will stop working.

#### android/src/debug/.../.../ReactNativeFlipper.java

//builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

More info can be found in the following issues:

https://github.com/facebook/flipper/issues/993

https://github.com/facebook/react-native/issues/28551

0
votes

change this line: form_data.append('file', data);

To form_data.append('file', JSON.stringify(data));

from https://github.com/react-native-image-picker/react-native-image-picker/issues/798

You need to add this uesCleartextTraffic="true" to the AndroidManifest.xml file found inside the dir android/app/src/main/AndroidManifest.xml

<application ... android:usesCleartextTraffic="true"> Then, Because of issue with Flipper Network.

I commented initializeFlipper(this, getReactNativeHost().getReactInstanceManager())

in this file /android/app/src/main/java/com/{your_project}/MainApplication.java

Also, commenting out line number 43 in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java

line43: builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

0
votes

If using expo and expo-image-picker, then the problem is only with the image type and nothing else.

In the latest updates, they removed the bug related to path (as other answers mention to change the beginning of the path which was correct for the older versions).

Now to remove the problem, we need to change the type only and is mentioned by other answers to use mime which works fine;

 import mime from 'mime'


const data = new FormData();
data.append('image', {
     uri: image.uri,
     name: image.uri.split('/').pop() // getting the text after the last slash which is the name of the image
    type: mime.getType(image.uri) // image.type returns 'image' but mime.getType(image.uri) returns 'image/jpeg' or whatever is the type

})