React-native: React Native 0.62.* [TypeError: Network request failed] on file upload

Created on 6 Apr 2020  ·  263Comments  ·  Source: facebook/react-native

Please provide all the information requested. Issues that do not follow this format are likely to stall.

Description

After upgrading from 0.61.4 to 0.62.0 the app will not upload files anymore from Android (all other requests are working fine)

React Native version:

0.62.0

Steps To Reproduce

  1. Install a fresh ReactNative app via CLI
  2. Upload a file to the emulator
  3. Try to upload a file using fetch
import Picker from "react-native-image-picker"
import {request, PERMISSIONS, RESULTS} from 'react-native-permissions';

class App extends React.Component {

  async componentDidMount() {

    try {
      await request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE)
      await Picker.launchImageLibrary({noData: true}, async (file) => {
        try {
           const body = new FormData()
           body.append("file", { type: file.type, size: file.fileSize, uri: `file://${file.path}`, name: file.fileName })
           const headers = { "content-type": "multipart/form-data", "accept": "application/json" }

          const req = await fetch("ANY_SERVER/upload/image", {
            method: "POST",
            headers,
            body
          })
          console.log(req.status)
        }  catch (e) {
          console.log(e)
        }
      })
    } catch (e) {
      console.log(e)
    }
  }

  render(){
    return <View/>
  }
}

Expected Results

The request should reach the server to upload the file

Snack, code example, screenshot, or link to a repository:

https://snack.expo.io/01W!bybf_
[Mon Apr 06 2020 21:29:18.704] LOG [TypeError: Network request failed]

Flipper React Native Team Attention Android

Most helpful comment

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java

All 263 comments

Same problem here!

Same problem !! I am stuck on this issue from last 2 days! Searched almost everything..

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

According to docs

When the attribute is set to "false", platform components (for example, HTTP and FTP stacks, DownloadManager, and MediaPlayer) will refuse the app's requests to use cleartext traffic. Third-party libraries are strongly encouraged to honor this setting as well. The key reason for avoiding cleartext traffic is the lack of confidentiality, authenticity, and protections against tampering; a network attacker can eavesdrop on transmitted data and also modify it without being detected.

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

    <application
      ...
      android:usesCleartextTraffic="true">

According to docs

When the attribute is set to "false", platform components (for example, HTTP and FTP stacks, DownloadManager, and MediaPlayer) will refuse the app's requests to use cleartext traffic. Third-party libraries are strongly encouraged to honor this setting as well. The key reason for avoiding cleartext traffic is the lack of confidentiality, authenticity, and protections against tampering; a network attacker can eavesdrop on transmitted data and also modify it without being detected.

I have tried it already. This is used when you are making request to a http server, but my server is running on https. It was running perfectly before upgrading to 0.62.
Something is wrong.

All other requests are working perfectly. Only file uploads are not working anymore.

All other requests are working perfectly. Only file uploads are not working anymore.

I faced too many issues when I tried upgrading to 0.62 even though I created a new app and moved my code into it. I rolled back to 0.61.5 till it gets stable :/

I am facing the same issue, for RN 0.62.0 and 0.62.1 throws this error: Network request filed.
All requests work except for the image post

I moved back to 0.61.5 :( No other choice left for now. If anyone needs help in downgrading to 0.61.5, refer to react-native-upgrade-helper.

Same happens here!

I faced same issue, it happens in Android, but works well in IOS.
I guess this issue about Flipper Network.

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

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

This issue occurs also on my end, and guess what it is only occurring in debug mode. Tried building in internalRelease and it works fine. I guess it is because of the auto/fast reload in debug mode which applies some flipper communication which seems to be related in this issue..

Another issue here is that there is no error in android logcat.. I've also spent some days researching how to fix this issue still no luck.

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java

Thanks for the issue @abumostafa. Does this occur in a fresh React Native template out of the box? If so this should be looked at otherwise feel free to close it.

:warning: Missing Reproducible Example
:information_source: It looks like your issue is missing a reproducible example. Please provide a Snack or a repository that demonstrates the issue you are reporting in a minimal, complete, and reproducible manner.
:warning: Using Old Version
:information_source: It looks like you are using an older version of React Native. Please upgrade to the latest version, and verify if the issue persists. If it does not, please let us know so we can close out this issue. This helps us ensure we are looking at issues that still exist in the current release.

Thanks for the issue @abumostafa. Does this occur in a fresh React Native template out of the box? If so this should be looked at otherwise feel free to close it.

This still occurs in latest fresh React Native template 0.62.1

Thanks for the issue @abumostafa. Does this occur in a fresh React Native template out of the box? If so this should be looked at otherwise feel free to close it.

This still occurs in the latest fresh React Native template 0.62.1

@safaiyeh
I can confirm. It's still happening in the latest fresh react native template 0.62.1

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

Still happening in 0.62.2, and this fixes temporarily the issue on Android

@abumostafa

*Try this *

try to implement "rn-fetch-blob"

````
import RNFetchBlob from "rn-fetch-blob";

RNFetchBlob.fetch('POST', , {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',}, [
{ name: 'profileimage', filename: this.state.filePath.fileName, data: RNFetchBlob.wrap(this.state.filePath.uri) },
{ name: 'uid', data: uidy },
{ name: 'dob', data:this.state.fDOB},
{ name: 'phonenumber', data:this.state.pnumber},
{ name: 'address', data:this.state.address},
{ name: 'gender', data: this.state.isgender},
{ name: 'username', data: this.state.fulname}
// custom content type
]).then((res) => {
console.log(res)
ResponseHelper.success('Updated');
this.setState({isstarting:false})
})
.catch((err) => {
this.setState({isstarting:false})
ResponseHelper.success('Server issue please try again');
console.log('err', error);
})
````

this will solve your issue

RNFetchBlob.wrap

Thanks. I have a question. Is this function RNFetchBlob.wrap converting the file to base64?

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

Thanks @abumostafa This workaround solution saved my lot of time. Already i spent lot of time on file upload error then i got your issue. By the way Did you know issue is fixed or not?

I pinged the Flipper team, the work for this will be tracked here: https://github.com/facebook/flipper/issues/993

I tried the two solutions proposed by @abumostafa and @alfianwahid; I tried to downgrade to 0.61.5; I tried to implement with fetch (I'm using axios); none worked. I am using version 0.62.1

I tried the two solutions proposed by @abumostafa and @alfianwahid; I tried to downgrade to 0.61.5; I tried to implement with fetch (I'm using axios); none worked. I am using version 0.62.1

did you try to rebuild the app after the changes??

@abumostafa I don't know if I did it right. But I deleted the node_modules folder, yarn.lock, ran the commands ./gradlew clean and ./gradlew cleanBuildCache and ran npx react-native run-android again.

I am experiencing the same issue at the moment on RN 0.61.4 and axios 0.19.2. Also tried commenting initializeFlipper(this); cleanBuildCache and still getting Network Error.

open the android folder and search for ReactNativeFlipper.java file and
comment the line number 43
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

In my case, I don't have that file in my project

In my case, I don't have that file in my project
do you have android folder
if you have search inside app folder

RNFetchBlob.wrap

Thanks. I have a question. Is this function RNFetchBlob.wrap converting the file to base64?

https://github.com/joltup/rn-fetch-blob/wiki/Fetch-API#class-rnfetchblob

Same here, for example trying to fetch("https://www.mocky.io/v2/5185415ba171ea3a00704eed") raises a TypeError: Network request failed.
It happens in Android only, both in debug and release, and both with remote debugging and without.
Adding android:usesCleartextTraffic="true" didn't help (but it's for non-SSL requests anyway).
Using RN 0.62.2.

Edit: fetching https://jsonplaceholder.typicode.com/todos/1 works! How can some sites work and others not?!

Update, after doing some tests, we came to the conclusion that it's due to failing SSL certificates. We don't know what's wrong with these, but the issue also happens in Postman with the "SSL certificate verification" option enabled. Could it be that the certificate authority is not in the phone's list?

Just spent the last day fighting with this issue. Prefixing my absolute path with "file://" so you end with three /'s sorted the issue out for me.

An example path:

file:///data/data/com.fake/cache/file-name.jpeg

Example of my code:

fetch(url, {
  method: "POST",
  body: {
    uri: 'file://' + file.absolutePath,
    type: file.type,
    name: file.name,
  },
  headers: headers,
  credentials: "include",
})

I am using react-native@^0.62.2

Has the fix been released? How do we update?

Still getting it in 0.62.2, are there any updates on this ?

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.
My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

Still happening in 0.62.2, and this fixes temporarily the issue on Android

This does fix it for now.

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

this made my day! works fine with RN 0.62.0. thank you!

Flipper has published an update, please check out the latest comment https://github.com/facebook/flipper/issues/993#issuecomment-619823916 Will react-native publish an update to reflect this fix?

Still getting a Network request failed with that new Flipper 0.39.0 when trying to fetch("https://www.mocky.io/v2/5185415ba171ea3a00704eed"), even though it works in Chrome/Firefox/Safari.

@antoinerousseau You might want to say it there... I haven't tested it out.

@aprilmintacpineda I posted in https://github.com/facebook/react-native/issues/26939 instead, seems more related, and I'm not sure if it's Flipper related?

This problem is solved by upgrading Flipper in this file

/yourproject/android/gradle.properties Line 28
gradle {.line-numbers} 25 android.enableJetifier=true 26 27 # Version of flipper SDK to use with React Native 28 FLIPPER_VERSION=0.41.0 //upgrade to latest flipper
See :
https://github.com/facebook/flipper/issues/993#issuecomment-619823916

i got the same issue with react 0.61.4

Thanks @alfianwahid
Solved my issue.

can we close this ticket?

Helped me as well 💪

@abumostafa , Thanks bro, that saved my 48 hours search

can we close this ticket?

I'm confused. Why are you wanting to close this issue if you only found a workaround and the issue was not fixed?

Hi everybody, I also tried with axios and fetch but none of this worked, also I tried commenting the Flipper line and upgrading it but also it doesn't have effect. If you guys still having problems with this, better try to do your POST request with XMLHttpRequest it worked for me.
Hope it helps.

This issue occurs also on my end, and guess what it is only occurring in debug mode. Tried building in internalRelease and it works fine. I guess it is because of the auto/fast reload in debug mode which applies some flipper communication which seems to be related in this issue..

Another issue here is that there is no error in android logcat.. I've also spent some days researching how to fix this issue still no luck.

How did you solve it ? @trglairnarra

I am facing the same issue, for RN 0.62.0 and 0.62.1 throws this error: Network request filed.
All requests work except for the image post

Same here. How did you solve it ? My app is running fine in release mode but not in build mode

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

You saved my day . Thanks a lot :) But is it safe to do so for future builds?

Hi, I am still getting the issue in 62.2.
Solutions tried

  1. android:usesCleartextTraffic="true" => Even my all other API working, also i have HTTP.
  2. commenting out line number 43
  3. no issue with "file://", => even without adding image, we just add json formdata still getting same error.

Hi, I am still getting the issue in 62.2.
Solutions tried

  1. android:usesCleartextTraffic="true" => Even my all other API working, also i have HTTP.
  2. commenting out line number 43
  3. no issue with "file://", => even without adding image, we just add json formdata still getting same error.

@jamisonrachford try to do your request with XMLHttpRequest

This problem is solved by upgrading Flipper in this file

/yourproject/android/gradle.properties Line 28

25  android.enableJetifier=true  
26  
27  # Version of flipper SDK to use with React Native 
28  FLIPPER_VERSION=0.41.0  //upgrade to latest flipper

See :
facebook/flipper#993 (comment)

manually making FLIPPER_VERSION=0.41.0 instead of using the default FLIPPER_VERSION=0.33.1 with RN 0.62.2 causes the build to fail (attached image). Am I missing a step in upgrading the flipper version?
gradle issues

I'm using expo. How can I solve this?

This problem is solved by upgrading Flipper in this file

/yourproject/android/gradle.properties Line 28

25  android.enableJetifier=true  
26  
27  # Version of flipper SDK to use with React Native 
28  FLIPPER_VERSION=0.41.0  //upgrade to latest flipper

See :
facebook/flipper#993 (comment)

Tks so much!

This problem is solved by upgrading Flipper in this file

/yourproject/android/gradle.properties Line 28

25  android.enableJetifier=true  
26  
27  # Version of flipper SDK to use with React Native 
28  FLIPPER_VERSION=0.41.0  //upgrade to latest flipper

See :
facebook/flipper#993 (comment)
Thanks!
This problem bothered me for two days

I am using expo client, there has to be a solution for it? I am searching for days and no avail of success, can anyone please help me how we can achieve this in expo?

@Hiti3 I'm using expo too. I also being searching for a solution. What I'm doing now is to send a base64 string (no formData) and decoding it at the server side:

Expo
`import * as ImagePicker from 'expo-image-picker';

// Image picker
export default async () => {
const permission = await ImagePicker.requestCameraRollPermissionsAsync();
if (permission.granted === 'false') return 'denied';
const options = { allowsEditing: true, base64: true };
const result = ImagePicker.launchImageLibraryAsync(options);
return result;
};
`

Server side
`
const sharp = require('sharp');
exports.uploadImage = async (req, res, next) => {
const { image } = req.body;
const {
type: imageType,
name: imageName,
base64: imageBase64,
path: imagePath,
resize,
} = image;

const base64Data = imageBase64.replace(data:image/${imageType};base64, '');

var img = new Buffer(base64Data, 'base64');
const path = __dirname + ./../../public/${imagePath}/${imageName};

if (resize) {
try {
await sharp(img)
.resize(500, 500)
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toFile(path);
} catch (err) {
console.log('write erro', err);
}
}
if (!resize) {
try {
await sharp(img).toFormat('jpeg').jpeg({ quality: 90 }).toFile(path);
} catch (err) {
console.log('write erro', err);
}
}
req.image = { imageType, imageName, imagePath };
next();
};
`

Help it helped. If you have any problem, please send me a message.

Thank you for the solution provided, this works as tested, I just want to
be sure again before I jump ship and lose a day maybe. And you are
uploading video or image if I understand correctly?

On Tue, 19 May 2020, 21:44 Gustavo Leite Silvano, notifications@github.com
wrote:

@Hiti3 https://github.com/Hiti3 I'm using expo too. I also being
searching for a solution. What I'm doing now is to send a base64 string (no
formData) and decoding it at the server side:

Expo
`import * as ImagePicker from 'expo-image-picker';

// Image picker
export default async () => {
const permission = await ImagePicker.requestCameraRollPermissionsAsync();
if (permission.granted === 'false') return 'denied';
const options = { allowsEditing: true, base64: true };
const result = ImagePicker.launchImageLibraryAsync(options);
return result;
};
`

Server side
`
const sharp = require('sharp');
exports.uploadImage = async (req, res, next) => {
const { image } = req.body;
const {
type: imageType,
name: imageName,
base64: imageBase64,
path: imagePath,
resize,
} = image;

const base64Data = imageBase64.replace(data:image/${imageType};base64,
'');

var img = new Buffer(base64Data, 'base64');
const path = __dirname + ./../../public/${imagePath}/${imageName};

if (resize) {
try {
await sharp(img)
.resize(500, 500)
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toFile(path);
} catch (err) {
console.log('write erro', err);
}
}
if (!resize) {
try {
await sharp(img).toFormat('jpeg').jpeg({ quality: 90 }).toFile(path);
} catch (err) {
console.log('write erro', err);
}
}
req.image = { imageType, imageName, imagePath };
next();
};
`

Help it helped. If you have any problem, please send me a message.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/facebook/react-native/issues/28551#issuecomment-631041471,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ACGFH2MSYJ2J5YDRASXISOTRSLOQFANCNFSM4MCRHIRA
.

0.41.0

Thank you so much.

This problem is solved by upgrading Flipper in this file
/yourproject/android/gradle.properties Line 28

25  android.enableJetifier=true  
26  
27  # Version of flipper SDK to use with React Native 
28  FLIPPER_VERSION=0.41.0  //upgrade to latest flipper

See :
facebook/flipper#993 (comment)

Tks so much!

@Hiti3 Just image. But I think that you can upload videos too.

Thanks @alfianwahid
but I used
FLIPPER_VERSION=0.44.0

i used to have the same problem, i tried every thing and and stuck on this for 4-5 days then i use RN-FETCH-BLOB package it really solved the problem of sending the files. use it you will never regret

After applying both of the above fixes, I am still getting Network request failed. In my case file getting updated on the server but it gives the error.

may be its a problem of the way you sending the data

may be its a problem of the way you sending the data

I am looking into it. But if the method of sending is not correct then why the data is getting updated on the server.

I have try every solution but no any success on android. I'm using 0.62.2
Screen Shot 2020-05-31 at 6 40 53 PM

@tamangsuresh Hey man, did you find a fix for this ?

@Brianop no man

感谢说升级Flipper的,我解决了

Hey, did anyone solved the issue ?, i am facing the same problem.

嘿,有人解决了这个问题吗?,我也面临着同样的问题。
You need to upgrade flipper to the latest

@liyuewen i have upgrade flipper in RN project and flipper too. But no any success.

@liyuewen 我在RN项目中也有鳍状肢的升级和鳍状肢。但是没有任何成功。

After the upgrade, you need to clear the Android cache

@liyuewen I have done that too. But no any luck.

This problem is solved by upgrading Flipper in this file

/yourproject/android/gradle.properties Line 28

25  android.enableJetifier=true  
26  
27  # Version of flipper SDK to use with React Native 
28  FLIPPER_VERSION=0.41.0  //upgrade to latest flipper

See :
facebook/flipper#993 (comment)
In my project flipper version is available on this location D:myProjectnode_modulesreact-nativetemplateandroidgradle.properties. I have updated flipper in the gradle at this location and the other gradle.properties which is located at /myProject/android/gradle.properties. Also data gets updated on the server and I have test it in Postman too working fine in Postman. I also have commented the code told by @abumostafa

@liyuewen 我也做到了。但没有任何运气。

My version is "react native": "^ 0.62.2", which is successful in the future

Updating Flipper to 0.45, solve the problem

I am not using Flipper anywhere, still having the same issue :(

I am not using Flipper anywhere, still having the same issue :(

Same here, using Expo.. This shouldn't be such an issue for so many people, especially when using managed workspace where the feature is ambiguously presented as a working function.

Anyone has updates on this issue. I have tried upgrading flipper, commenting out flipper in mainactivity. Still having this issue in android.
Returns [TypeError: network request failed].
But same code works fine in iOS

Anyone has updates on this issue. I have tried upgrading flipper, commenting out flipper in mainactivity. Still having this issue in android.
Returns [TypeError: network request failed].
But same code works fine in iOS

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

Removing this line in MainApplication.java works. Issue is still there in debug build. but it works in release build.

Anyone has updates on this issue. I have tried upgrading flipper, commenting out flipper in mainactivity. Still having this issue in android.
Returns [TypeError: network request failed].
But same code works fine in iOS

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

Removing this line in MainApplication.java works. Issue is still there in debug build. but it works in release build.

Thanks, I never tried testing in release build. I'll try that today.

I have react-native v59. So, what can people who don't use the Flipper do? Are any updates?

Here's all the relevant data I could think to pull from my app. I'm experiencing the same problem, on the iOS simulator.

RN 0.62.2, Flipper 0.46.0, on an ejected Expo app.

  // Turn the recording into a multipart form request with recording = the contents of our file.
  let fileUri = recording.getURI();
  if (!fileUri) {
    throw new Error('fileUri is null, it should always be initialized before reaching this point.');
  }

  let body = new FormData();
  body.append('recording', {
    uri: fileUri,
    name: 'voice-command.mp4',
    type: 'audio/mp4'
  });

  // Kick off the transcription job.
  var response;
  try {
    response = await fetch(
      'http://localhost:5000/api/v0/commands/transcription/start',
      {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
        },
        body,
      },
    );
  } catch (error) {
    console.error(error);
    throw error;
  }

TypeError: Network request failed
http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:32085:31
dispatchEvent@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:34645:31
setReadyState@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:33729:33
__didCompleteResponse@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:33556:29
emit@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:9744:42
__callFunction@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:5491:49
http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:5213:31
__guard@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:5445:15
callFunctionReturnFlushedQueue@http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:5212:21
callFunctionReturnFlushedQueue@[native code]

Info.plist is set up to allow localhost requests.

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>

My package.json:

{
  "name": "EstimateMobileApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "ios": "react-native run-ios",
    "android": "react-native run-android",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.10",
    "@react-navigation/native": "^5.4.2",
    "@react-navigation/stack": "^5.3.9",
    "@types/react-native-vector-icons": "^6.4.5",
    "expo": "^37.0.12",
    "expo-av": "^8.1.0",
    "react": "^16.11.0",
    "react-native": "^0.62.2",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-reanimated": "^1.8.0",
    "react-native-safe-area-context": "^1.0.2",
    "react-native-screens": "^2.7.0",
    "react-native-unimodules": "^0.9.1",
    "react-native-vector-icons": "^6.6.0",
    "tailwind-rn": "^1.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/runtime": "^7.9.0",
    "@react-native-community/eslint-config": "^0.0.5",
    "@types/jest": "^25.2.3",
    "@types/react": "^16.9.35",
    "@types/react-native": "^0.62.10",
    "@types/react-test-renderer": "^16.9.2",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.58.0",
    "react-test-renderer": "16.11.0",
    "tailwindcss": "^1.4.6",
    "typescript": "^3.9.3"
  },
  "jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-(native|universal|navigation)-(.*)|@react-native-community/(.*)|@react-navigation/(.*))"
    ]
  }
}

And my Podfile:

platform :ios, '10.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
require_relative '../node_modules/react-native-unimodules/cocoapods.rb'

def flipper_pods()
  flipperkit_version = '0.46.0'
  pod 'FlipperKit', '~>' + flipperkit_version, :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitLayoutPlugin', '~>' + flipperkit_version, :configuration => 'Debug'
  pod 'FlipperKit/SKIOSNetworkPlugin', '~>' + flipperkit_version, :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitUserDefaultsPlugin', '~>' + flipperkit_version, :configuration => 'Debug'
  pod 'FlipperKit/FlipperKitReactPlugin', '~>' + flipperkit_version, :configuration => 'Debug'
end

# Post Install processing for Flipper
def flipper_post_install(installer)
  file_name = Dir.glob("*.xcodeproj")[0]
  app_project = Xcodeproj::Project.open(file_name)
  app_project.native_targets.each do |target|
    target.build_configurations.each do |config|
      cflags = config.build_settings['OTHER_CFLAGS'] || '$(inherited) '
      unless cflags.include? '-DFB_SONARKIT_ENABLED=1'
        puts 'Adding -DFB_SONARKIT_ENABLED=1 in OTHER_CFLAGS...'
        cflags << '-DFB_SONARKIT_ENABLED=1'
      end
      config.build_settings['OTHER_CFLAGS'] = cflags
    end
    app_project.save
  end
  installer.pods_project.targets.each do |target|
    if target.name == 'YogaKit'
      target.build_configurations.each do |config|
        config.build_settings['SWIFT_VERSION'] = '4.1'
      end
    end
  end
  installer.pods_project.save
end

target 'EstimateMobileApp' do
  # Pods for EstimateMobileApp
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/'
  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'ReactCommon/callinvoker', :path => "../node_modules/react-native/ReactCommon"
  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga', :modular_headers => true

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

  target 'EstimateMobileAppTests' do
    inherit! :complete
    # Pods for testing
  end

  use_native_modules!
  use_unimodules!

  flipper_pods()
  post_install do |installer|
    flipper_post_install(installer)
  end
end

target 'EstimateMobileApp-tvOS' do
  # Pods for EstimateMobileApp-tvOS

  target 'EstimateMobileApp-tvOSTests' do
    inherit! :search_paths
    # Pods for testing
  end
end

I have react-native v59. So, what can people who don't use the Flipper do? Are any updates?

I didn't have this issue in previous versions. Your issue might be something different I think. Are you using https url?

I have react-native v59. So, what can people who don't use the Flipper do? Are any updates?

I didn't have this issue in previous versions. Your issue might be something different I think. Are you using https url?

Yep, https.
Are there any limitations for the formData object in RN, for example, it could be a string length or formData size? It looks like the RN intercept this request and throws this error

I have react-native v59. So, what can people who don't use the Flipper do? Are any updates?

I didn't have this issue in previous versions. Your issue might be something different I think. Are you using https url?

Yep, https.
Are there any limitations for the formData object in RN, for example, it could be a string length or formData size? It looks like the RN intercept this request and throws this error

I am not aware of any such limitations. Can you share the code? And did this work on iOS?

I need to reach such request body structure:

{
    "user_uuid":"9a137...",
    "contract_uuid":"881d9...",
    "files":[
        {"document_type_id":"20","document_type_title":"test1","private_flag":"0","file":{}},
        {"document_type_id":"21","document_type_title":"test2","private_flag":"1","file":{}},
        {"document_type_id":"22","document_type_title":"test3","private_flag":"1","file":{}}
    ]
}

where the file is a JS file object with name, type, uri, size, etc. fields

const fileArrayToSend = await Promise.all(
            fileSelect.map(async (file, index) => {
                const documentTypeNum = Number(documentType[index]) || 0;

                return {
                    document_type_id: documentTypeNum,
                    document_type_title: customType ? customType[index] : null,
                    private_flag: isPrivate[index] ? 1 : 0,
                    file: {
                        name: file.name, 
                        type: file.type,
                        uri: file.uri, 
                        size: file.size
                    }
                };
            })
        );
let body = {
    contract_uuid: contract.uuid,
    user_uuid: userUUID
};

const formData = new FormData();
const appendToFormData = (formData, object) => {
    for (let [key, value] of Object.entries(object)) {
        if (value) {
            formData.append(key, value);
        }
    }
};
appendToFormData(formData, body);

fileArrayToSend.forEach((file, index) => {
    formData.append(`files[${index}]`, file, file.file.name);
});
let response = await Axios.post(`${config.apiEndpoint}/store_document_request_action`, formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
});

image

I had same this issue in my project with react-native version 0.62.
I updated flipper to "0.41.0" and it worked.
In gradle.properities
FLIPPER_VERSION=0.41.0

I had same this issue in my project with react-native version 0.62.
I updated flipper to "0.41.0" and it worked.
In gradle.properities
FLIPPER_VERSION=0.41.0

Can you please mention the path of gradle.properties, gradle.properties in android do not contain flipper version. But gradle.properties in react android folder have flipper version.

@nharis7 it's in /android/gradle.properties
Annotation 2020-06-12 210640
But what's your version of react-native? flipper is only in react-native version 0.62 and above. There's no flipper in old versions.

@nharis7 it's in /android/gradle.properties
Annotation 2020-06-12 210640
But what's your version of react-native? flipper is only in react-native version 0.62 and above. There's no flipper in old versions.

Currently I am on 0.62.2 and I have upgraded my project from 0.61 in my /android/gradle.properties. I have created a new project with it now I can see flipper version in /android/gradle.properties. I'll migrate all my stuff to new project and will see if this issues gets solved or not.

THIS SOLUTION WORKED FOR ME
https://github.com/axios/axios/issues/1567#issuecomment-518118223

Upgrading flipper fixes it! (i upgraded to 0.46.0)

I tried all the way above!
only upgrade flipper to 0.46 can fix it!

image

"dependencies": {
    "@react-native-community/async-storage": "^1.11.0",
    "@react-native-community/cameraroll": "^1.7.2",
    "@react-native-community/masked-view": "^0.1.10",
    "@react-navigation/drawer": "^5.8.1",
    "@react-navigation/material-bottom-tabs": "^5.2.9",
    "@react-navigation/native": "^5.5.0",
    "@react-navigation/stack": "^5.4.1",
    "axios": "^0.19.2",
    "mime-types": "^2.1.27",
    "path": "^0.12.7",
    "query-string": "^6.13.1",
    "react": "16.11.0",
    "react-native": "0.62.2",
    "react-native-animatable": "^1.3.3",
    "react-native-animate-loading-button": "^1.0.3",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-image-picker": "^2.3.1",
    "react-native-image-resizer": "^1.2.3",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-paper": "^3.10.1",
    "react-native-reanimated": "^1.9.0",
    "react-native-safe-area-context": "^3.0.2",
    "react-native-screens": "^2.8.0",
    "react-native-swiper": "^1.6.0",
    "react-native-vector-icons": "^6.6.0"
  },

This problem is solved by upgrading Flipper in this file

/yourproject/android/gradle.properties Line 28

25  android.enableJetifier=true  
26  
27  # Version of flipper SDK to use with React Native 
28  FLIPPER_VERSION=0.41.0  //upgrade to latest flipper

See :
facebook/flipper#993 (comment)

It worked pretty well, that solved the problem on android, thank u so much.

Eu enfrentei o mesmo problema, isso acontece no Android, mas funciona bem no IOS.
Eu acho que esta questão sobre a Rede Flipper.

Por enquanto, comentei
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())

neste arquivo
/android/app/src/main/java/com/{your_project}/MainApplication.java

It worked for me :)

I faced same issue, it happens in Android, but works well in IOS.
I guess this issue about Flipper Network.

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

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

i tested with this its then i was able to upload file

thanks @alfianwahid

Upgrading flipper to 0.46.0 fixes it!

In
android\gradle.properties

This issue took me more than 5 hours to resolve. I was about to give up when I was finally able to resolve the issue.

The issue that I was facing which is close to what you are mentioning is that I was getting NetworkError when using expo-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. :)

When you got a network error with formData you must check the formData correctness. It's very important.

android/gradle.properties
upgrade Fliper
FLIPPER_VERSION=0.41.0

People who are still facing issue they can do like this

let data = new FormData();

data.append('action', 'ADD');
data.append('param', 0);
data.append('secondParam', 0);
data.append('file', new Blob([payload], { type: 'text/csv' }));

// this works
let request = new XMLHttpRequest();
request.open('POST', url);
request.send(data);

it will work (:+1: (:100:

Looks like lots of people have been able to workaround this by updating their flipper version. Which is great. But also a lot of people went through pain to find this issue and get unblocked.

So question: What would make it easier to discover this? Pinned issue? Is a closed issue (since it seems like this resolved?) still discoverable? Stack Overflow link? It seems like this is resolved, but we don't want people to continue to waste time trying to find a known solution.

This should get closed as soon as the upgrade lands - https://github.com/facebook/react-native/pull/29033. Until that happens, we may consider pinning it.

I still have the same issue after updated the flipper version to 0.46.0

Myself also having the same issue. Someone please help us

  const imageUrl = 'http://febbler.com/20150425_114106.jpg';
    // if (true) {
    // const fileToUpload = res;
    const formData = new FormData();
    formData.append('name', 'Image Upload');
    formData.append('file_attachment', {
        uri: imageUrl,
        type: "image/jpeg",
        name: 'floral-spring-natural-landscape-wild-260nw-1274207287.jpg'
    });
    Axios({
        url: URL + '/VideosController/upload',
        method: 'POST',
        data: formData,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data'
        },
    }).then(
        response => {
            alert('res' + JSON.stringify(response.data));
        },
        error => {
            alert('check+ ' + error);
            console.warn(error);
        })
        .catch(error => {
            alert('No error' + error);
        });

I dont what i did wrong can some one help me to fix ??

If I updated FLIPPER_VERSION=0.41.0 application itself not even opening.

Maybe this helps someone out that is still having issues with this.
Are you using WAF (Web Application Firewall) policies from Microsoft? If so; they have a bug (or React Native, not sure who is to blame exactly) that blocks requests with a similar But only sometimes, and only on iOS. The multipart-form boundary that is generated at the lowest level in RN sometimes contains characters (probably a .) that the policies block.

This costs us many days to figure out. Microsoft acknowledged it. We disabled the related WAF-policy to work around the issue. This doesn't happen in PostMan for instance. That generates a different boundary than RN does.

Upgrading flipper to 0.44.0 And React-native 0.63.0 , I still have same problem

I fixed it by commenting a line in the
/android/app/src/debug/java/com/{your-app-name}/ReactNativeFlipper.java
file.
this is only fix that worked for me!

new NetworkingModule.CustomClientBuilder() {
@Override
public void apply(OkHttpClient.Builder builder) {
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
}
});

If you tried everything above and nothing helps you, and you using image picker and form-data try adding this in image picker options:
``` js
let options = {
title: 'Select Image',
noData: true,
maxWidth: 500,
maxHeight: 500,
};
ImagePicker.showImagePicker(options, response => {
.
.

Form data should look like this then:

```js
 const formData = new FormData();
        formData.append('avatar', {
          uri: response.uri, 
          name: response.fileName,
          type: 'image/jpeg',
        });

I faced same issue, it happens in Android, but works well in IOS.
I guess this issue about Flipper Network.

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

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

I had same this issue in my project with react-native version 0.62.
I updated flipper to "0.41.0" and it worked.
In gradle.properities
FLIPPER_VERSION=0.41.0

Both of these works for me. But only use one solution. Thanks both. @alfianwahid @dmobisoft
Think FLIPPER_VERSION=0.41.0 better solution.

Is anyone from React native developers aware of this trembling issue, as anyone with MANAGED WORKSPACE (ex. Expo) is unable to implement proposed "solutions" with RN Flipper hack.. Any proposed solutions from your side for managed workspaces such as Expo?

Hi @Hiti3 I would suggest creating an issue on the Expo repository here: https://github.com/expo/expo, as the solutions here would not apply to a managed workspace.

cc @brentvatne

@Hiti3 - this doesn't impact managed expo apps because flipper is not integrated in them. if you are seeing this error it is for other reasons than those mentioned in this issue, and your best course of action if you're unable to find a solution is to create a mcve and post it to https://github.com/expo/expo/issues

For me also not working giving error [TypeError: Network request failed]

CODE:

const username = this.state.values.username;
const lastname = this.state.values.lastname;
const images_path= this.state.images_list[0].url.uri;

                    const data = new FormData();
                   // data.append('name', 'Image Upload');
                    data.append('email', email);
                    data.append('username', username);
                    data.append('file',  { uri:images_path, name: 'image.jpg', type: 'image/jpeg/jpg',path:images_path);

                    let res = await fetch(
                        'IP-Address/cowsoncloud/admin/cowRegister.php',{
                        method: 'POST',
                        body: data,
                        headers: {
                            'Accept': "application/json",
                            'Content-Type': 'multipart/form-data',
                        },
                        })
                    .then(response => response.json())
                        .then(responseJson => {
                        console.log('upload succes',+responseJson);
                        alert('Upload success!'+JSON.stringify(responseJson));
                        })
                        .catch(error => {
                        console.log('upload error', error);
                        alert('Upload failed!'+error);
                        });

                    } else {
                    alert('Please Select File first');
                    }
                };

For me also not working giving error [TypeError: Network request failed]

CODE:

const username = this.state.values.username;
const lastname = this.state.values.lastname;
const images_path= this.state.images_list[0].url.uri;

                    const data = new FormData();
                   // data.append('name', 'Image Upload');
                    data.append('email', email);
                    data.append('username', username);
                    data.append('file',  { uri:images_path, name: 'image.jpg', type: 'image/jpeg/jpg',path:images_path);

                    let res = await fetch(
                        'IP-Address/cowsoncloud/admin/cowRegister.php',{
                        method: 'POST',
                        body: data,
                        headers: {
                            'Accept': "application/json",
                            'Content-Type': 'multipart/form-data',
                        },
                        })
                    .then(response => response.json())
                        .then(responseJson => {
                        console.log('upload succes',+responseJson);
                        alert('Upload success!'+JSON.stringify(responseJson));
                        })
                        .catch(error => {
                        console.log('upload error', error);
                        alert('Upload failed!'+error);
                        });

                    } else {
                    alert('Please Select File first');
                    }
                };

You gave IP address as a string URL is a wrong check once again.

when I post without file(image) i will work fine, when I sending with image file that time showing error [TypeError: Network request failed]; don t wary about URL

I fixed it by commenting a line in the
/android/app/src/debug/java/com/{your-app-name}/ReactNativeFlipper.java
file.
this is only fix that worked for me!

new NetworkingModule.CustomClientBuilder() {
@override
public void apply(OkHttpClient.Builder builder) {
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
}
});

Try this one worked for me

I also have same issue. I use hack for this https://github.com/facebook/react-native/issues/29021#issuecomment-662196480.

If you have flipper version 0.37.0, bump it into 0.41.0, It worked on mine.

I faced same issue, it happens in Android, but works well in IOS.
I guess this issue about Flipper Network.

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

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

Thank you very much it worked perfectly in my project.
I just want to know how could you figure out that the Flipper initializer was the cause for the bug ?

@alfianwahid

Just for sharing. For android, you can try to upgrade flipper version to 0.41, then it will be working fine. But for IOS, I still face the same issue even the IOS flipper version is 0.41.5. So for IOS, I manually update the node_modules/react-native/Libraries/Network/RCTNetworkTask.mm and it is working on IOS now.

please can you ell me how to upgrade flipper FLIPPER_VERSION=0.33.1 to 0.41

@sureshhallyali , you can update FLIPPER_VERSION=0.41.0 in android/gradle.properties file. After that clean the android build and run-android again.

Just for sharing, I'm using Flipper 0.50 on my Ubuntu and updating android/gradle.properties to FLIPPER_VERSION=0.50.0 worked just fine too.

I have tried all the solutions above (from upgrading flipper to commenting out to deleting debug folder and all), and none worked for me, I am still getting network error although the image gets saved in server. react-native 0.62.2, I have been trying for 2 days now, this is really frustrating...

this is my code

let formData = new FormData();

    formData.append('id', hospitalId);
    formData.append('date', dataObj.date);
    formData.append('questions', dataObj.questions);

    dataObj.attachments.forEach((attachment) => formData.append('attachments[]', attachment));

    this.props.submit(formData);

Submit (in short)

try {
      const res = await axios.post(url, formData, {
        headers: {
          Authorization: token ? `Bearer ${token}` : null,
          deviceId: getUniqueId(),
          Accept: 'application/json',
          'Content-Type': `multipart/form-data`,
        },
      });
      console.log('SUBMIT RES >>>> ', res.data);
    } catch (err) {
      console.log('errrr >>>> ', err.response);
      console.log('errrr >>>> ', err);
    }

Has this issue been fixed in 0.63.1 ?

UPDATE:
Upgraded to 0.63.2 still, the problem persists

Just for sharing, I'm using Flipper 0.50 on my Ubuntu and updating android/gradle.properties to FLIPPER_VERSION=0.50.0 worked just fine too.

@vinifraga , how you upgrade the Flipper version in IOS? I know how to upgrade on android but not sure how to upgrade from ios/podfile there?

Hi guys try out rn-fetch-blob this works for me
i was using Axios to upload image but it was not working for android so after so many search i found this package and it worked

Link here for package

Tried everything (others lib too rn-fetch-upload, rn-background-upload, ...), image upload are not working on iOS and it's fine on Android. Uploading on S3 using pre signed URL always returning me this (was working well on RN -v 0.59.x, and not anymore on RN -v 0.61.x:
````
"
EntityTooLarge
Your proposed upload exceeds the maximum allowed size
2025220
2023115
{...}
5n+{...}
"

@MayoudP try rn-fetch-blob maybe this will works

Thanks @abumostafa

I tried this all solution but not working
1 : need to add
uesCleartextTraffic="true" to the AndroidManifest.xml file found inside the dir android/app/src/main/AndroidManifest.xml
for handle http and https

2: need to comment
// initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
in this file /android/app/src/main/java/com/{your_project}/MainApplication.java
3: need to comment
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
int his file android/app/src/debug/java/com/{your_project}/ReactNativeFlipper.java
4: some one told upgrade react native to 63.2 that also done
5: FLIPPER version upgrading to 50.0

need to try now one : rn-fetch-blob
https://github.com/facebook/react-native/issues/29493

3: need to comment
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

finally worked in android

Using rn-fetch-blob for the API calls where form data is needed works (iOS confirmed, not sure yet about Android), I just replaced my regular fetch calls there (see readme):

https://github.com/joltup/rn-fetch-blob

Does this problem really persist for like 4 months?

@MayoudP try rn-fetch-blob maybe this will works

Nop, it didn't worked, didn't succeed to make it works using a pre signed URL and S3...

Just for sharing. For android, you can try to upgrade flipper version to 0.41, then it will be working fine. But for IOS, I still face the same issue even the IOS flipper version is 0.41.5. So for IOS, I manually update the node_modules/react-native/Libraries/Network/RCTNetworkTask.mm and it is working on IOS now.

@anthony1110 What do you update in node_modules/react-native/Libraries/Network/RCTNetworkTask.mm?

@MayoudP try rn-fetch-blob maybe this will works

Nop, it didn't worked, didn't succeed to make it works using a pre signed URL and S3...

Just RNFS works rn

@andrekovac , you can follow this thread and follow the IOS and android solution. https://github.com/facebook/react-native/issues/29021#issuecomment-664030881

Applying the patch @anthony1110 mentioned doesn't work for me. Still getting network errors.

But a solution (for React Native 0.63) seems to be coming soon: https://github.com/facebook/react-native/issues/29364#issuecomment-664526253

@andrekovac , dont follow my patch, that one is hack. Bad solution. You should follow the update https://github.com/facebook/react-native/issues/29364#issuecomment-663005914 for IOS issue.

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

i try this and works 100%

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

This works (Y)

This bug gonna drive me crazy
All solutions above is not working

Hey @victor012888 have tried the rn-fetch-blob

I use the upload FLIPPER_VERSION=0.50.0 way finally solved
My problem is INSTALL_FAILED_INSUFFICIENT_STORAGE cause the new packges are too big
After add more RAM for vitual machine everything is working on

I have try all, still have problem.
not only debug version but release version.

I have solve my issue now!
①update FLIPPER_VERSION=0.52.0 latest

②formData code like this
let formData = new FormData();
this.state.pics.map((value,index) => {
console.log(value)
console.log(index)
let file = {uri:value.uri, type: 'multipart/form-data',name:value.uri.substr(value.uri.length-10,10)};
formData.append('file'+index,file)
})

type must be 'multipart/form-data' , the same with post header.


hope can help someone

I use the upload FLIPPER_VERSION=0.50.0 way finally solved
My problem is INSTALL_FAILED_INSUFFICIENT_STORAGE cause the new packges are too big
After add more RAM for vitual machine everything is working on

how to update FLIPPER

I'm having this issue, started on RN63+ and I do not have flipper. Flipper is completely uninstalled.

It also only happens for file uploads with multipart/form-data, type is defined. But the request is skipped every time on android.

Hello, I'm using expo 38 with RN 0.62.2
I'm using the bare workflow, so i can edit the native code.
I have the same issues even though i tried every fix listed:

  • Updated Flipper in gradle.properties to 0.52.0
  • commented out the initializeFlipper line in MainApplication.java
  • Tried every possible configuration for the type of the 'file' formData param.

My code looks like this

export const createFileUploadFormData = (file, body) => {
  const isAndroid = Platform.OS === 'android'
  const fileUri = isAndroid ? file.uri : file.uri.replace('file://', '')
  const fileType = mime.getType(fileUri) || file.type
  const formData = new FormData()
  formData.append('file', {
    name: file.fileName,
    type: fileType,
    uri: fileUri,
  })
  if (body && body.length) {
    Object.keys(body).forEach((key) => {
      formData.append(key, body[key])
    })
  }
  return formData
}

Any idea about what I might be missing out ?

Unfortunately, the mentioned workarounds about commenting Flipper lines of code and such did not work for me.

I managed to get this working though by using rn-fetch-blob.

Below is a piece of code showing how I've used that library to upload a pdf file:

const response = await RNFetchBlob.fetch(
  'POST',
  'http://192.168.0.20:3000/files',
  {
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data',
  }, [
    {
      name: 'file',
      originalname: 'avataroriginalname',
      filename: 'avatar.pdf',
      type: 'application/pdf',
      data: RNFetchBlob.wrap(<path-to-file>),
    },
  ]
)

I faced same issue, it happens in Android, but works well in IOS.
I guess this issue about Flipper Network.

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

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

Bro its work perfectly, Thank you 👍

Hello, I'm using expo 38 with RN 0.62.2
I'm using the bare workflow, so i can edit the native code.
I have the same issues even though i tried every fix listed:

  • Updated Flipper in gradle.properties to 0.52.0
  • commented out the initializeFlipper line in MainApplication.java
  • Tried every possible configuration for the type of the 'file' formData param.

[...]

Ahhhh I've found out what I was missing out on !
In my case i was feeding the wrong header to my fetch call, due to an old copy paste >.<
I was using

const headers = {
  Accept: 'application/json',
  'Content-Type': 'application/json',
}

when instead it should have been:

const headers = {
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data',
  }

The tricky part is that:

  1. this mistake works on iOS
  2. it had always been as such on Android for months with no trouble uploading files

It seems that since the last updates of RN, such mistakes are not tolerated anymore using Android.

I faced same issue, it happens in Android, but works well in IOS.
I guess this issue about Flipper Network.

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

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

I was getting stream closed when trying to upload to S3 with XHR and this solves the issue and thank you 👍

I upgraded Flipper to version 0.51.2 and it worked for me.

I upgraded Flipper to version 0.51.2 and it worked for me.

Hello @omid-ebrahimi , how did you upgrade Flipper version?

Thank You

same issue 0.63.2

I upgraded Flipper to version 0.51.2 and it worked for me.

Hello @omid-ebrahimi , how did you upgrade Flipper version?

Thank You

Go to android/gradle.properties and add this line

FLIPPER_VERSION=0.52.1

You should have the following lines in your android/app/build.gradle:

dependencies {
    // ....

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    // ...
}

I upgraded Flipper to version 0.51.2 and it worked for me.

Hello @omid-ebrahimi , how did you upgrade Flipper version?
Thank You

Go to android/gradle.properties and add this line

FLIPPER_VERSION=0.52.1

You should have the following lines in your android/app/build.gradle:

dependencies {
    // ....

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    // ...
}

@omid-ebrahimi upgrading flipper also solves the issue thank you, And I have opened an issue on this at StackOverflow with the bounty, please submit this answer there and I can award the bounty to you.

issue link

I upgrade fliipper to version 52.0
and use fetch and it worked for me
But when use axios.post don't work
And when use axios like
axios({ method:'post , data : file , url:'something ',............. })
it work fine

And don't set header
'Content-Type': 'multipart/form-data'
also it will work fine

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

@abumostafa The solution you provided is effective, but it still does not work for files starting with "file:///".
E.g:

  • This can work: formData.append('files', {uri:'https://xxx.jpg', type:'image/jpeg', name:'test.jpeg' })
  • This does not work: formData.append('files', {uri:'file:///xxx.jpg', type:'image/jpeg', name:'test.jpeg' })

My react native version:

"dependencies": {
    "react": "^16.11.0",
    "react-native": "^0.62.2"
  }

the same issue tried upgrading flipper but not working.

{
 "react": "16.13.1",
  "react-native": "0.63.2",
}

How about iOS?

Having this issue on iOS as well. Tried changing Flipper's version from 0.33.1 to 0.50.0 and above in my Podfile. This is happening for me on

{
  "react": "16.11.0",
  "react-native": "0.62.2",
}

@abumostafa's suggestion made it work for Android but still not able to get it to work on iOS.

EDIT: Upgraded to react-native: 0.63.2 still the same issue.

Changing the Flipper versions doesn't work for me. I tried commenting out the line which may helped but also faced the same issue. My workaround is to use a WebView and injectJavascript to do the uploads. This hack works well for me.

My workaround is using <WebView> and injecting javascript.. When I want to upload a new file, I will pass the relevant parameters to a string function builder generateUploadCodes() and it will generate a string which will be injected to the webview.

  function generateUploadCodes(name, data) {
    return `function upload() {
      let formData = new FormData();
      formData.append('file', new Blob(["${data}"], {type: 'text/csv'}));

      let xhr = new XMLHttpRequest();
      xhr.open("post","https://myuploadserver.com");
      xhr.setRequestHeader("Authorization", "Bearer ${accessToken}");
      xhr.responseType = "json";
      xhr.onload = () => {
         window.ReactNativeWebView.postMessage(xhr.response);
      };
      xhr.send(formData);
    }
    upload(); 
    `;
  }

With that I can just call

let toInject = generateUploadCodes("mydata.txt", "somedata");
webRef.current.injectJavascript(toInject);

To obtain the response from the upload, we can use webview.ReactNativeWebView.postMessage('our response');. Then process the response through WebView's onMessage handler.

Before all of that, we to create our ref and our WebView component first like this

  const webview = useRef(null);

  <WebView
        ref={webview}
        source={{html: 'hi'}}
        injectedJavaScript={''}
        javaScriptEnabledAndroid={true}
        javaScriptEnabled={true}
        onMessage={event => {
              console.log(event.nativeEvent.data);
        }}
      />

Bringing together all the fixes here, hopefully we can get a fix for this merged to core soon:

iOS: Revert a PR, requires modifying node_modules: https://github.com/facebook/react-native/issues/29364#issuecomment-671565181, PR submitted here for the fix: https://github.com/facebook/react-native/pull/29595

Android: Upgrade Flipper version https://github.com/facebook/react-native/issues/28551#issuecomment-674351386, PR raised https://github.com/facebook/react-native/pull/29787

If anyone is still facing problem in RN Version 0.62 or higher, solution is:
You must have to give uri, name & type of the media you are uploading.

formData.append('media_incident', {
          uri: image.path,
          type: image.mime,
          name: 'filename.jpg',
        });

Then go to Line number 43 and comment this line:
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
at android/app/src/debug/java/com/"project name"/ReactNativeFlipper.java

I have spent close to 8 hours digging the solution for the error.

If anyone is still facing problem in RN Version 0.62 or higher, solution is:
You must have to give uri, name & type of the media you are uploading.

formData.append('media_incident', {
          uri: image.path,
          type: image.mime,
          name: 'filename.jpg',
        });

Then go to Line number 43 and comment this line:
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
at android/app/src/debug/java/com/"project name"/ReactNativeFlipper.java

I have spent close to 8 hours digging the solution for the error.

Yep, that was the case for me too, confirmed it here: https://github.com/facebook/react-native/issues/29364#issuecomment-679370449

Flipper upgrade PR raised by FB https://github.com/facebook/react-native/pull/29787

Bringing together all the fixes here, hopefully we can get a fix for this merged to core soon:

iOS: Revert a PR, requires modifying node_modules: https://github.com/facebook/react-native/issues/29364#issuecomment-671565181, PR submitted here for the fix: https://github.com/facebook/react-native/pull/29595

Android: Upgrade Flipper version https://github.com/facebook/react-native/issues/28551#issuecomment-674351386, PR raised https://github.com/facebook/react-native/pull/29787

I was having the same issue and none of the solutions here worked for me.

What worked for was that I am just missing the mime_type of my upload.

Be sure to have these data correctly:

  • uri
  • name
  • type

Worked with upgrading flipper to FLIPPER_VERSION=0.52.1.

Change in this file - android/gradle.properties and run yarn android.

fetch

let uriParts = this.state.pickedFileUri.split('.');
let fileType = uriParts[uriParts.length - 1];
const file = {
            uri: this.state.pickedFileUri, // works with fileurl like file:///.....
            name: `myFile.${fileType}`,
            type: `text/${fileType}`,
        };

const data = new FormData();
data.append('file', file);
return fetch(url, {
        method: 'POST',
        body: data,
});

package.json

   "react": "16.11.0",
    "react-native": "0.62.2",

Is there a workaround for this using Expo?

anyone solve this problem ? already try every method like comment some flipper command, upgrading flipper on graddle.properties, even i downgrade my RN from 0.63 to 0.62 still got this error. Already stuck on this error for 2 days . When i try to post data without file to my API it works fine, but when i try to upload file like image to my API i got this errors

@safaiyeh still didnt work for me sir, i already try it all .

If anyone is still facing problem in RN Version 0.62 or higher, solution is:
You must have to give uri, name & type of the media you are uploading.

formData.append('media_incident', {
          uri: image.path,
          type: image.mime,
          name: 'filename.jpg',
        });

Then go to Line number 43 and comment this line:
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
at android/app/src/debug/java/com/"project name"/ReactNativeFlipper.java

I have spent close to 8 hours digging the solution for the error.

i did same, but still facing same issue. iam using
"react": "16.13.1",
"react-native": "0.63.1",

@sadhruva I have the same environment like you and this solved the issue for me

I'm experiencing the same issue. These type of errors are frustrating since there is pretty much nothing we can do other than waiting for a fixed release.

I've tried:

  • Commenting the line on the java file

  • Changing my flipper version

  • Writing the code in 2 different ways

And it still does not work. The weird thing is that the form DOES work in other parts of my app, but on that particular screen it does not work (only on android, because on iPhone it does work as expected).

So, seems like the only thing I can do right now is to continue development for iOS only and delay the android release.

Life is life... I guess.

I'm experiencing the same issue. These type of errors are frustrating since there is pretty much nothing we can do other than waiting for a fixed release.

I've tried:

  • Commenting the line on the java file
  • Changing my flipper version
  • Writing the code in 2 different ways

And it still does not work. The weird thing is that the form DOES work in other parts of my app, but on that particular screen it does not work (only on android, because on iPhone it does work as expected).

So, seems like the only thing I can do right now is to continue development for iOS only and delay the android release.

Life is life... I guess.

Experiencing the same problem.However it's weird that the same function works fine with react, thus I went to check the network packages and found that my react webAPP network request package goes with a content-type:multipart/form-data header,while RN goes with content-type:application/form-data.
So I editted my request function like this:
await fetch(url, { method: 'POST', headers: { 'Content-Type': 'multipart/form-data', }, body: formData, })
Then include type&name in the formData
let formData = new FormData(); formData.append('file', {uri: fileUri,type:fileType,name:fileName});
Don't know why,but it just works miraculously.

i am using react native version 0.63.2 and followed these steps to fix the problem
using react-native-cli

1 - in android/app/src/main/java/com/{yourProject}/MainApplication.java
comment -> initializeFlipper(this, getReactNativeHost().getReactInstanceManager())

2 - in android/app/src/debug/java/com/{yourProject}/ReactNativeFlipper.java
comment in line 43 -> builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));

3 - in android/gradle.properties
changeFLIPPER_VERSION=0.37.0 to FLIPPER_VERSION=0.52.1

4 - in android/app/build.gradle
overwrite the current Flipper dependencies to

  dependencies {
    // ....

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    // ...
  }

and after all these steps -> npx react-native run-android or yarn android

5 - in my post upload request

  const data = new FormData();
  // Android need to add "file:///" to work

  const path =
    Platform.OS === 'android' ? `file:///${image?.path}` : image?.path;

    const file = { // use name, type, uri as object keys
      name: image?.fileName,
      type: image?.type,
      uri: path,
    };


    data.append('file', file);

    // using axios
    const response = await api.post(
          'apiurl',
          data,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          },
        );

Hope this helps

@mathrocha12100 can you please format properly your comment? Some code seems to be out of place, I might try to do it step by step.

The problem is that I really don't want to mess up the config for android. But anyways, please do format your answer properly to help everyone that encounters this issue (including me).

Cheers.

Still does not work.

@dlogvin
I faced this issue yesterday and fix it as @omid-ebrahimi said [upgrade Flipper], plus comment this line
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); at ReactNativeFlipper.java

Clean Build folders [ios, android]
then build again it's work for me well :)

@dlogvin
I faced this issue yesterday and fix it as @omid-ebrahimi said [upgrade Flipper], plus comment this line
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); at ReactNativeFlipper.java

Clean Build folders [ios, android]
then build again it's work for me well :)

How do you exactly upgrade flipper?

edit: I already tried replacing the FLIPPER version and commenting the lines, but still nothing. Actually, in the debug version of the app, the images don't load after commenting the lines. This is a complete mess...

@dlogvin in android/gradle.properties
change FLIPPER_VERSION=0.37.0 to FLIPPER_VERSION=0.52.1

here's react and react-native version if you wondering

 "react": "16.13.1",
  "react-native": "0.63.2",

@anastely I did it... still nothing :(

I'm giving up...

@dlogvin I'm tried to load images from the server and it's loaded, So I'm sorry :(

if your project open source I can give it a check

I apologize, but the project is not open source. I have tried to upload files, the form works in other screens, but in this specific one it does not. I'll have to wait for RN's update, meanwhile I'll just work out the iPhone version and keep the Android's version in BETA.

work for me I change flipper version in gradle.setting file FLIPPER_VERSION=0.30.2 to FLIPPER_VERSION=0.52.1 then clean gradlew and run project.
in react native use XMLHttpRequest method.
export let dataWithImage = async (endPoint, params) => {
let token = await AsyncStorage.getItem('token');
let xhr = new XMLHttpRequest();
let formData = new FormData();
for (let key in params) {
formData.append(key, params[key]);
}
xhr.withCredentials = true;
xhr.addEventListener('readystatechange', function () {
if (this.readyState === 4) {
console.log(this.responseText, '===> this is response');
}
});
xhr.open('POST', url + endPoint);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.send(formData);
};

I am facing a similar issue with a POST request over my server (HTTPS), works ok for iOS but not on android. Tried to disabling flipper and upgrading it and still having the same issue. Tried with another server, like (https://jsonplaceholder.typicode.com/) and seems to be working as expected.

The error description doesn't tell me too much "Network Error" , Already checked the Internet permissions and set android:usesCleartextTraffic="true" on the android manifest.

Same issue with fetch or axios.

For IOS in
node_modules/react-native/Libraries/Image/RCTLocalAssetImageLoader.mm file

Replace Below

  • -(RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
    size:(CGSize)size
    scale:(CGFloat)scale
    resizeMode:(RCTResizeMode)resizeMode
    progressHandler:(RCTImageLoaderProgressBlock)progressHandler
    partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
    completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
    {
    UIImage *image = RCTImageFromLocalAssetURL(imageURL);
    if (image) {
    if (progressHandler) {
    progressHandler(1, 1);
    }
    completionHandler(nil, image);
    } else {
    NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
    RCTLogWarn(@"%@", message);
    completionHandler(RCTErrorWithMessage(message), nil);
    }

    return nil;
    }

With

  • -(RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
    size:(CGSize)size
    scale:(CGFloat)scale
    resizeMode:(RCTResizeMode)resizeMode
    progressHandler:(RCTImageLoaderProgressBlock)progressHandler
    partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
    completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
    {
    __block auto cancelled = std::make_shared>(false);
    RCTExecuteOnMainQueue(^{
    if (cancelled->load()) {
    return;
    }

    UIImage *image = RCTImageFromLocalAssetURL(imageURL);
    if (image) {
    if (progressHandler) {
    progressHandler(1, 1);
    }
    completionHandler(nil, image);
    } else {
    NSString *message = [NSString stringWithFormat:@"Could not find image %@", imageURL];
    RCTLogWarn(@"%@", message);
    completionHandler(RCTErrorWithMessage(message), nil);
    }
    });

    return ^{
    cancelled->store(true);
    };
    }

This..

Like and Love , if it work 👍

Hi all a fix has just been merged to master: https://github.com/facebook/react-native/commit/d8b70b19b39ead4dd41895d666d116a43c56474e

There was also an iOS fix already committed into master.

I have put in a back port request here: https://github.com/react-native-community/releases/issues/203#issuecomment-695052285, expect this in 0.63.3 or 0.64

@safaiyeh I'm ecstatic right now by this comment you added. I hope to put my hands on development back for android ASAP.

Cheers.

Thank you very much.

Yup, glad everyone is gonna get the fix soon 🙇‍♂️ been hectic a bit for me too chasing down the right people and such. Getting closer!

Thank you, I´m waiting for it.
For now I´m using the same workaround made by @mathrocha12100.

I am facing similar issue on iOS. Not particular to files but on iOS my api calls fails randomly, same api request will work one time, other time fails with undefined in response.
on android its working fine all the time
I am using axios 0.19.2, tried fetch but same result
React native 0.62.2

@vajid-khan have you confirmed that the issue is on your front-end side? Try using postman or Insomnia to check if its your backend, your react native code or if it is the framework itself. I have not experienced any issues with the other API's requests at all.

@dlogvin yes I have confirmed with postman. With postman I am getting response everytime, even android is working all the time. I am facing this only on iOS

@dlogvin yes I have confirmed with postman. With postman I am getting response everytime, even android is working all the time. I am facing this only on iOS

@vajid-khan that's kind of weird. This specific issue is based on requests of POST methods with files. Might as well work out some debugging, probably headers or something like that.

@dlogvin yes I have confirmed with postman. With postman I am getting response everytime, even android is working all the time. I am facing this only on iOS

@vajid-khan that's kind of weird. This specific issue is based on requests of POST methods with files. Might as well work out some debugging, probably headers or something like that.

I confirm his issue, I've faced it too in "ios" after upgrading Flipper to 0.54.0 as @safaiyeh mentioned in PR!


Edit:
When I open xCode and send the request i can see this in the logs

[native] Missing request token for request: <NSURLRequest: 0x600000dda4e0> { URL: file:///Users/anastely/Library/Developer/CoreSimulator/Devices/13C4E525-8577-44A3-A5F3-F6693B9CDFF6/data/Containers/Data/Application/FD4541BF-805A-4420-9AF3-0A9A55854126/tmp/react-native-image-crop-picker/7E060441-D875-4883-BD34-89872ECB3CB7.jpg }

So I got this after searching #https://github.com/facebook/react-native/commit/31980094107ed37f8de70972dbcc319cc9a26339
And replacing it as they said,
the post request work in some cases!
In my app I send an image in post request, if I choose an image from the _default one in the simulator,_ the request did not get any response _'not work as before'_ but the above issue disappeared,
So I don't know whats going on!
If can anybody here to test this case in his physical device and let us know!

@mathrocha12100 thank u very much , your answer solve my problem

Same issue, tried everything said here! Still not working!

Try this

let formData = new FormData();
formData.append('file', {
     name: filename,
     uri: uri // For android the path should start like this "content://". If uri starts with "file://", replace with "content://" 
     type: type
}
axios.post(URL, formData, { headers: { 'Content-Type': 'multipart/form-data'}})

Try this

let formData = new FormData();
formData.append('file', {
     name: filename,
     uri: uri // For android the path should start like this "content://". If uri starts with "file://", replace with "content://" 
     type: type
}
axios.post(URL, formData, { headers: { 'Content-Type': 'multipart/form-data'}})

This is not the issue. Other forms in my app work except a specific one. This is not a path issue.

Try this

let formData = new FormData();
formData.append('file', {
     name: filename,
     uri: uri // For android the path should start like this "content://". If uri starts with "file://", replace with "content://" 
     type: type
}
axios.post(URL, formData, { headers: { 'Content-Type': 'multipart/form-data'}})

This is not the issue. Other forms in my app work except a specific one. This is not a path issue.

Yes other post method will work except File upload because it related to Flipper. Change the Flipper version to 0.58 and run gradlew clean in android folder. For me, after this, only changing to content:// works for me otherwise gives Network err.

@safaiyeh Any update on this?
I want to release my App :(

Whoever is still struggling with this issue. it's happening because of Flipper network plugin.
I disabled it and things work just fine.

My workaround to make this work is commenting out line number 43

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

in this file android/app/src/debug/java/com/**/ReactNativeFlipper.java

Still an issue in react native 0.63. This solution worked for me.

Same issue, tried everything said here! Still not working!
@mathrocha12100 's Step one fixed my issue!
android/app/src/main/java/com/{yourProject}/MainApplication.java comment -> initializeFlipper(this, getReactNativeHost().getReactInstanceManager())

Same problem here!

First attempt to correct the problem:

update Flipper to 0.46.0 (did not work)
update Flipper to 0.52.0 (did not work)
comment on line 43 of ReactNativeFlipper.java (did not work)
delete the debug folder in android / app / src / debug (did not work)

Versions installed in my project:

"react": "16.13.1",
"react-native": "0.63.2",
"axios": "^ 0.20.0",

We need an urgent solution

Same problem here!

First attempt to correct the problem:

update Flipper to 0.46.0 (did not work)
update Flipper to 0.52.0 (did not work)
comment on line 43 of ReactNativeFlipper.java (did not work)
delete the debug folder in android / app / src / debug (did not work)

Versions installed in my project:

"react": "16.13.1",
"react-native": "0.63.2",
"axios": "^ 0.20.0",

We need an urgent solution

I absolutely agree with this... we need an urgent PERMANENT solution. This is delaying my project, in other words, it is affecting me a lot. It is getting really annoying, the wait is getting longer and longer. When is the update coming out?

Thank you everyone for your patience! The fix has been released with 0.63.3, make sure to revert any work around you made and properly upgrade!

Make sure you clean your gradle build as well.

If any new issues occurred please create a new issue 🎉🤟😁

Thank you everyone for your patience! The fix has been released with 0.63.3, make sure to revert any work around you made and properly upgrade!

Make sure you clean your gradle build as well.

If any new issues occurred please create a new issue 🎉🤟😁

Upgraded, still have the same issue. Should we change the gradle.properties? mine indicates FLIPPER_VERSION=0.33.1

Update: changed the Flipper version to: 0.54.0, still does not work.

people that did not follow any type of fix provided above and that upgraded, please confirm if this is not an issue I'm experiencing myself. This did not fix the problem. @murilokrugner ??

@dlogvin I reverted the modifications and upgraded to version 63.3 but it still didn't work, do we have to update Flipper to some version?

In my project Flipper is in version: 0.37.0

Then the update did not work.

@safaiyeh

The update did not work.

It's a simple matter, just an upload and it doesn't work. Let's open a new issue

It's a simple matter, just an upload and it doesn't work. Let's open a new issue

It is a simple matter which is URGENT to fix. A lot of apps are affected by this, uploading files is a must for a lot of services.

We should def open a new issue.

You can use this for the full diff https://react-native-community.github.io/upgrade-helper/

Already made use of that, nothing helped.

Maybe it's a stupid question:"D
But how you upgrade to the last release 0.63.3?
using helper and copy-paste dif?

Maybe it's a stupid question:"D
But how you upgrade to the last release 0.63.3?
using helper and copy-paste dif?

npx react-native upgrade try, but I'm 99.99% sure the "fix" won't work.

I updated my project from 63.2 to 63.3 and Flipper from 0.37.0 to 0.54.0

But it's still not working

Am I doing something wrong?

After upgrade to 0.63.3

I got some strange issues in iOS when i choose an image from the file system image and send the request not work! but when i download a random image then try again it's work very well!! "Simulator 13.3"

Android works very well ;)

So, the issue has not been solved yet.

File uploads are not a thing in this new version.

Please reopen the issue @safaiyeh

Let's open a new issue. With a minimum repro with the latest react native.

One for @anastely ios issue and

@dlogvin Android issue.

Please tag me on the issue.

All the solutions I found on the internet, so far none have worked.

I have been facing this problem since version 0.62 of React Native.

I had a project in which I needed to upload files but the deadline was short, so the alternative was to convert the file to a Base64 String and send it to the backend.

However, fixing this problem is extremely urgent.

All the solutions I found on the internet, so far none have worked.

I have been facing this problem since version 0.62 of React Native.

I had a project in which I needed to upload files but the deadline was short, so the alternative was to convert the file to a Base64 String and send it to the backend.

However, fixing this problem is extremely urgent.

I agree, this is a critical issue and it affects ALL apps that make use of file uploads.

@safaiyeh yes, I will open an issue. Will do when I arrive home.

Guys, I'm not buying it. It worked!

Solution that worked for me: I updated React Native to 0.63.3 and Flipper to 0.54.0 but it still wasn't working.

I restarted the Android emulator and opened it again. and it worked !!

Thank you all!

Guys, I'm not buying it. It worked!

Solution that worked for me: I updated React Native to 0.63.3 and Flipper to 0.54.0 but it still wasn't working.

I restarted the Android emulator and opened it again. and it worked !!

Thank you all!

Interesting, thing is... I built the app for release... tested in physical device, same thing. I tried using the debug apk, same error "network error".

Not resolved yet. Will open issue soon.

Guys, I'm not buying it. It worked!

Solution that worked for me: I updated React Native to 0.63.3 and Flipper to 0.54.0 but it still wasn't working.

I restarted the Android emulator and opened it again. and it worked !!

Thank you all!

Please try running in physical device on debug and release build please

Guys, I'm not buying it. It worked!
Solution that worked for me: I updated React Native to 0.63.3 and Flipper to 0.54.0 but it still wasn't working.
I restarted the Android emulator and opened it again. and it worked !!
Thank you all!

Please try running in physical device on debug and release build please

@dlogvin It also works on a physical device, I believe it is something in cache

Guys, I'm not buying it. It worked!
Solution that worked for me: I updated React Native to 0.63.3 and Flipper to 0.54.0 but it still wasn't working.
I restarted the Android emulator and opened it again. and it worked !!
Thank you all!

Please try running in physical device on debug and release build please

@dlogvin It also works on a physical device, I believe it is something in cache

Im glad its solved for you, but on my side... I even tried a clean build, still no luck...

If anyone is still facing problem in RN Version 0.62 or higher, solution is:
You must have to give uri, name & type of the media you are uploading.

formData.append('media_incident', {
          uri: image.path,
          type: image.mime,
          name: 'filename.jpg',
        });

Then go to Line number 43 and comment this line:
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
at android/app/src/debug/java/com/"project name"/ReactNativeFlipper.java

I have spent close to 8 hours digging the solution for the error.

After trying all the hacks discussed above, this was the one which saved my day. Thanks a lot!

upgrading to 0.63.3 worked for me finally

in my case, previously this upload form code is working fine:

form.append('file', {
    uri: file,
    type: filetype,
    name: filename,
})

then I did install some other dependencies and then it returns the network error.
so I had to change the type with an explicit prefix:

form.append('file', {
    uri: file,
    type: 'audio/' + filetype,
    name: filename,
})

RN 63.3 has fixed this issue. It works!

upgrading to 63.3 solved for me also

Nope..

RN 63.3 works basically because its flipper version uses 0.54.0.
If RN 63.3 still not works, we should check
android:
FLIPPER_VERSION in android/gradle.properties file
iOS:
pod install --repo-update

I'm using RN 0.63.3 and updated the FLIPPER_VERSION to 0.54.0 but it's still not working. Any other solution available?

did it ,its not because of the flipper version ,I'm using react -native 0.62.2 and flipper version :0.33.1,commented out line 43 in android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java and made sure the type in upload is specified properly,

We should use this tools to upgrade to RN 63.3. Make sure every merge is correctly.
https://react-native-community.github.io/upgrade-helper/

SOLVED!
Change version of react navite in package.json:
"react-native": "0.63.3"
On ANDROID:
android/gradle.properties
Change Flipper version:
FLIPPER_VERSION=0.54.0
After that, uninstall the app on the device and run the project again. :)
IOS steps:
https://react-native-community.github.io/upgrade-helper/ (just select the lastest version of RN or use 0.63.3)

Maybe this will save someone. A similar error occurred(don't upload files!!!) with any network requests. In my case, the problem was in the ssl certificate of my https server. The term of the expired certificate, and that was the cause of the error.

RN: 0.61.5

I tried everything suggested in this thread and looked everywhere for suggestions and nothing. Finally, I realized the issue. Maybe it will help someone else.

It was actually my fault... I was calling the Image picker in a child component. The user picked there images. Clicked save, which returned them back to the previous component. They would complete a form and the images would get uploaded after they completed the form.

The problem was, in the child component, I called ImagePicker.clear(). It was a bit berried and so I didn't see it right away. I got the same "network error could not read file for uri" everyone else got so I think for my specific case, I was very mislead thinking there was some other issue happening.

I guess the good thing is I ended up upgrading my react native version, flipper, and Gradle to the lastest. So there is that. On the other hand I lost 3 days to this. Programming is weird.

If anyone is still facing problem in RN Version 0.62 or higher, solution is:
You must have to give uri, name & type of the media you are uploading.

formData.append('media_incident', {
          uri: image.path,
          type: image.mime,
          name: 'filename.jpg',
        });

Then go to Line number 43 and comment this line:
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
at android/app/src/debug/java/com/"project name"/ReactNativeFlipper.java
I have spent close to 8 hours digging the solution for the error.

After trying all the hacks discussed above, this was the one which saved my day. Thanks a lot!

Don`t work

Was miss-guided by some post on the internet which stated that the file:// part on the path for android should be removed before setting it to the URI for the form data. Using the path as is and removing the builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); as mentioned above, worked for me for react version 0.62.2 for both android and ios

still have the problem, using RN 0.63.3 flipper 0.54.0, uploading photos fine but when uploading video have network error, ill using another method like @murilokrugner said, since my deadline short too

still have the problem, using RN 0.63.3 flipper 0.54.0, uploading photos fine but when uploading video have network error, ill using another method like @murilokrugner said, since my deadline short too

for u guys if u still having this issue i've simple solutions:

  1. install rn-fetch-blob follow their instruction https://github.com/joltup/rn-fetch-blob
  2. then follow this instruction https://github.com/joltup/rn-fetch-blob#multipartform-data-example-post-form-data-with-file-and-data

mine is working well

@abumostafa you're a legend. Thank you so much.

Anyone still facing this issue with 0.63.3 and newest flipper - change fetch to XMLHttpRequest. Works perfectly fine.

Still Facing same issue using :
RN 0.63.3
flipper 0.54.0

I commented out line 43 in android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

Still same issue i tried almost everything not working .

To share my solution is to decode with camera in base64 and then send it on the server in that format. I am utterly dissappointed how in 2020 some miniscule and simple features that are promoted from the developers, just simply do not work for..years.

TLDR: Anyone having issues sending a file, try to convert to base64 & send it.

Was this page helpful?
0 / 5 - 0 ratings