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

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]

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 81
  • Comments: 308 (17 by maintainers)

Commits related to this issue

Most upvoted comments

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

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

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.

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 : https://github.com/facebook/flipper/issues/993#issuecomment-619823916

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

Same problem here!

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.

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

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

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

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

resolved network issue in android in fomdata append uri with file://

formData.append(video${idx}, { name: img.name, type: video/${ext}, uri: file://${img.sourceURL}, })

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

upgrading to 0.63.3 worked for me finally

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.

@mirfanahmed and @kylanhurt I fixed this issue by hard coding the file type extention. Take a look at the uriParts variable and fileType variable. Let me know if this works for you.

  const createFormData = (photo) => {
    const data = new FormData();
    const uriParts = photo.uri.split('.');
    const fileType = uriParts[uriParts.length - 1];

    data.append('image', {
      name: 'profilePic',
      type: `image/${fileType}`,
      uri: Platform.OS === 'ios' ? photo.uri.replace('file://', '') : photo.uri,
    });

    return data;
  };

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

Same happens here!

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

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 .

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

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.

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

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)

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?

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

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.

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 face same issue in RN 0.65.1. why close the issue? have any solution?

If anyone is still facing issue. Simply go to android/gradle.properties and update FLIPPER_VERSION to 0.52.1 . that’s it!

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 🎉🤟😁

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!

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

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

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

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:\myProject\node_modules\react-native\template\android\gradle.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

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

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.

Still having same issues in RN 64.1

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

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 👍

Upgrading flipper to 0.46.0 fixes it!

In android\gradle.properties

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

Updating Flipper to 0.45, solve the problem

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.

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

Hello. I am facing a problem from past 2 days in android that whenever I try to hit an api through axios by simply sending a formdata I get a network error. I have updated to expo sdk 41 and react native version 0.63.3 but it still it gives me this error. I need urgent help.

@Siddharth2212 still got this issue, but on the ios

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.

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.

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

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

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

android/gradle.properties upgrade Fliper FLIPPER_VERSION=0.41.0

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

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

can we close this ticket?

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?

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?!

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

i getting this in RN 0.64 , while i individually upload image or video but when i upload with image and video text it works fine

react native 0.64 ✅ adding the content type in headers solved the issue for me.

fetch(urls[i], {
              method: 'put',
              headers: {'Content-Type': `${contentType}; charset=utf-8`},
              body: binaryFile,
            })

@mirfanahmed and @kylanhurt I fixed this issue by hard coding the file type extention. Take a look at the uriParts variable and fileType variable. Let me know if this works for you.

  const createFormData = (photo) => {
    const data = new FormData();
    const uriParts = photo.uri.split('.');
    const fileType = uriParts[uriParts.length - 1];

    data.append('image', {
      name: 'profilePic',
      type: `image/${fileType}`,
      uri: Platform.OS === 'ios' ? photo.uri.replace('file://', '') : photo.uri,
    });

    return data;
  };

This works for me

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

Hey @abumostafa, What in the case of managed workflow like Expo where there is no access to native project files, what could be the possible solution in that case ?

RN Version - 0.63.4 Flipper - 0.54.0. I have facing same issue. I have changed Flipper version to 0.41.0. Now issue fixed. Thanks

So I think figured out my issue, posting here in case anyone else ran into the same issue. I was running my client and my python webserver on the same laptop. After looking at

sudo tcpdump -i en0 -v -n | grep 192.168.0.103

it was my server that was silently sending the FINISHED and RST (connection reset by peer) tcp codes. Found post1 and post2 blaming the python GIL for time mismatch since I was running the full stack on a laptop. Switched my backend to my (old) desktop and was able to upload 145 mb no problem.

Good luck to everyone out there!

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

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/

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

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,
})

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…

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!

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?

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'}})

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

@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!

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

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<std::atomic<bool>>(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 👍

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

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

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”,

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

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

@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…

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

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?

Has this issue been fixed in 0.63.1 ?

UPDATE: Upgraded to 0.63.2 still, the problem persists

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.

If you tried everything above and nothing helps you, and you using image picker and form-data try adding this in image picker options:

     let options = {
     title: 'Select Image',
     noData: true,
     maxWidth: 500,
     maxHeight: 500,
   };
   ImagePicker.showImagePicker(options, response => {
        .
        .

Form data should look like this then:

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

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 (👍 (💯

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.

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

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.

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

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?