request formData to API, gets “Network Error” in axios while uploading image
Asked Answered
C

19

17

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);
    });
Councilman answered 12/4, 2020 at 17:35 Comment(2)
Here is an easy way to upload images or videos with axios https://mcmap.net/q/400485/-how-do-you-send-images-to-node-js-with-axiosAirspeed
also consider making a helper function javascript const getFormDataFromObj = (formObj) => { const payload = new FormData(); for (const key in formObj) { if (formObj.hasOwnProperty(key)) { payload.append(key, formObj[key]); } } return payload; }; const multipartFormData = getFormDataFromObj(formObj) Cathee
C
4

"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.

Councilman answered 17/4, 2020 at 4:31 Comment(5)
github.com/facebook/react-native/issues/28551 @srinivas you can check this link maybe its solve your issueCouncilman
What I understand after seeing that page by updating the FLIPPER_VERSION=0.41.0 it should get resolve but if I updated the application not even opening.Tahsildar
I was wasting 2 days because of this issue. Thank god now it works fine. Thank you for this solution @GovindMaheshwari.Primary
not working it may delete the androidmanifest.xmlBombshell
thank you, you save my day. my code work before and suddenly not working even tough there is no change. and after delete the debug folder it works againShanon
S
20

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 :)

Simonides answered 29/3, 2021 at 4:40 Comment(6)
stumble upon the same mime-type thing. It is really surprising.Symposiarch
You save my day, the exact problem is file uri formatSalverform
For me the problem with android was only wrong mime type. In IOS works ok with only type: 'jpg' but in android gives network error. The file uri was correct in both OSsDutch
I am getting this issue. I can put image/png.Kant
Thank you so much! The mime type was my issue, also I had to switch to axios as converting to the image to blob using fetch was causing issues with the whatwg-fetchBurgundy
in my case file picker returns identical uri for android and iosDania
R
13

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

Rhythm answered 1/7, 2020 at 14:34 Comment(0)
C
7

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

Crescint answered 20/10, 2020 at 12:56 Comment(6)
this solution worked for me but at the same time, I am worried about commenting on this line will thereafter affect?Tout
no, I already done that in my project and its in production now so don't worryCrescint
do i need to comment the line in ReactNativeFlipper.java also?Corduroy
try to follow this answer, if not working then go to the ReactNativeFlipper.java and comment line number 43 FlipperOkhttpInterceptorCrescint
flipper is a platform tool for debugging React Native projects and its safe to completely remove it from your project, ive done it on most projects and saved myself a lot of troubles. This is only of course if you are not planning to take your time to learn how to benefit from from itWestland
how would i do this on expo?Aziza
S
7

in my case, the solution was to change to

const headers = {
    accept: 'application/json',
    'content-type': 'multipart/form-data',
};
Stridor answered 3/6, 2022 at 8:24 Comment(0)
T
6

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.

Tamtam answered 4/9, 2020 at 2:59 Comment(1)
The type should not be multipart/form-data. Instead, it should be the photo type, e.g: image/jpeg.Wold
C
4

"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.

Councilman answered 17/4, 2020 at 4:31 Comment(5)
github.com/facebook/react-native/issues/28551 @srinivas you can check this link maybe its solve your issueCouncilman
What I understand after seeing that page by updating the FLIPPER_VERSION=0.41.0 it should get resolve but if I updated the application not even opening.Tahsildar
I was wasting 2 days because of this issue. Thank god now it works fine. Thank you for this solution @GovindMaheshwari.Primary
not working it may delete the androidmanifest.xmlBombshell
thank you, you save my day. my code work before and suddenly not working even tough there is no change. and after delete the debug folder it works againShanon
N
2

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?

Nereid answered 12/7, 2020 at 16:43 Comment(1)
The correct answer with minimal changes. although the path name is android/app/src/..... .Hyaloplasm
R
1

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));

Rubescent answered 1/6, 2021 at 0:25 Comment(0)
C
1

Also got the same issue. I spent almost 4 days to find reason. So in my case it was Content-Type: multipart/form-data. I forgot indicate it. In Android it should be indicated explicitly...

Courtship answered 6/9, 2022 at 11:29 Comment(1)
It not woriking for meMoorland
A
0

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

})
Airspeed answered 15/6, 2021 at 7:21 Comment(1)
Full answer of how to upload images or videos https://mcmap.net/q/400485/-how-do-you-send-images-to-node-js-with-axiosAirspeed
S
0

In my case, after debbuging for a while, the issue was in nginx.
The image was "too big".

I Had to add annotations to the Kubernetes ingress:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/proxy-body-size: 20m
....

It was a bit tricky to debug since the request never got through the load balancer (nginx) to the Api service. The "Network error" message didn't help a lot either.

Selinaselinda answered 12/11, 2021 at 22:37 Comment(0)
D
0

I am using Expo SDK 42 (react-native v0.63). And I was using the expo-document-picker library to pick the documents & upload to server.

This is the code I am using to open the picker & get the metadata about the file.

const result = await DocumentPicker.getDocumentAsync({
    type: 'image/*',
    copyToCacheDirectory: false,
    multiple: false,
});

if (result.type === 'success') {
    const name_split = result.name.split('.');
    const ext = name_split[name_split.length - 1];
    // result.uri = 'file://' + result.uri;
    result.type = helper.get_mime_type(ext);
    delete result.size;
}

(You can write your function to get the mime type from the file extension or use some library from npm)

And this is the code I am using to upload the file to server:

const formdata = new FormData();
formdata.append('custom_param', 'value');
formdata.append('file', result); // 'result' is from previous code snippet

const headers = {
    accept: 'application/json',
    'content-type': 'multipart/form-data',
};

const opts = {
    method: 'POST',
    url: 'your backend endpoint',
    headers: headers,
    data: formdata,
};
return await axios.request(axiosopts);

The above code is the working code. I want to explain what I did wrong initially that was causing the Network Error in axios.

I had set copyToCacheDirectory to true initially and the uri I was getting in the result was in the format /data/path/to/file.jpeg. And I also tried appending file:// to beginning of the uri but it didn't work.

I then set copyToCacheDirectory to false and the uri I was getting in the result was in the format content://path/to/file.jpeg. And this didn't cause any Network Error in axios.

Dvorak answered 16/12, 2021 at 14:22 Comment(0)
S
0

I have faced this error as well. I found out that I got this error because the file path is wrong and axios couldn't find the file. It is a weird error message when the uri is wrong though but that's what actually has happened. So double checking the uri of the file would fix the issue. Mainly consider file://.

Sublingual answered 2/3, 2022 at 12:43 Comment(0)
C
0

I faced the same issue.

After capturing the photo wait for 10sec then start uploading. It worked for me.

Cytochrome answered 23/6, 2022 at 8:57 Comment(0)
P
0

After two days of searching for a solution, I found that the problem was in my rn-fetch-blob library, Changed it to in package.json dependencies

"rn-fetch-blob": "^0.12.0",

fix my Netowk issue and app crash on uploading. I am using

react-native-image-crop-picker
Peraza answered 19/11, 2022 at 18:52 Comment(0)
N
0

always send image and file in formdata in post api through axios in react js and react native

enter image description here

Blockquote

Neoterize answered 23/11, 2022 at 9:38 Comment(0)
D
0

REACT NATIVE SOLUTION USING AXIOS

I face the same issue after upgrading react native cli project. I'm using "react-native": "0.70.6", "react": "18.1.0", "axios": "^1.1.3" AND FLIPPER_VERSION=0.125.0

The below code solves my issue

const imageData = image;
const form = new FormData();
form.append("ProfileImage", {
  type: imageData.mime,
  uri: imageData.path,
  name: imageData.path.split("/").pop(),
});

axios({
  method: "put",
  url: `${URL}/api/UploadPhoto`,
  data: formData,
  headers: {
    "Content-Type": "multipart/form-data",
    "cache-control": "no-cache",
  },
  processData: false,
  contentType: false,
  mimeType: "multipart/form-data",
});

For me, I didn't comment on any line from the /android/app/src/main/java/com/{your_project}/MainApplication.java

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

Also not changed FLIPPER_VERSION

Dredger answered 10/12, 2022 at 8:45 Comment(1)
this is not the answer. its just your problem.Won
R
0

A really weird solution to this that worked for me was

**turning off/ stopping any form of debugger that was active.**

Be it React Native Debugger, the Android Studio Debugger (In case you're building a hybrid app like I am), Flipper etc.

Reason being that: The React Native Debugger can sometimes interfere with network requests because it acts as a proxy between your app and the server. When your app makes a network request, it passes through the debugger before reaching the server. In some cases, this can cause issues like:

Network timing issues: The debugger might introduce latency, which can result in timeouts or other network-related problems.

CORS issues: The debugger might not handle Cross-Origin Resource Sharing (CORS) headers properly, which could lead to CORS-related errors when making requests to external servers.

SSL/TLS issues: The debugger might not support certain SSL/TLS configurations, which can cause issues when making requests to HTTPS endpoints.

WebSocket issues: The debugger might not fully support WebSocket connections, causing issues when using real-time communication.

Altered request/response headers: The debugger might unintentionally modify request or response headers, which could lead to unexpected behavior or errors.

Rucksack answered 10/5, 2023 at 6:36 Comment(0)
M
0

In my case axios was throwing NETWORK ERROR. I followed below procedure

let localUri = response.uri;
let filename = response.fileName ?? localUri.split('/').pop() ?? '🖼';
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;

const image = {
  uri: localUri,
  name: filename,
  type,
};

let formData = new FormData();
  formData.append("image", image); 

And my issue was solved!

Methodism answered 10/7, 2024 at 10:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.