facebook / react-native

A framework for building native applications using React
https://reactnative.dev
MIT License
118.91k stars 24.3k forks source link

React Native 0.62.* [TypeError: Network request failed] on file upload #28551

Closed abumostafa closed 4 years ago

abumostafa commented 4 years ago

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]

mcanikhilprajapati commented 4 years ago

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

MadalitsoNyemba commented 4 years ago

Upgrading flipper to 0.46.0 fixes it!

In android\gradle.properties

s-xync commented 4 years ago

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

arthedza commented 4 years ago

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

ebhdeveloper commented 4 years ago

android/gradle.properties upgrade Fliper FLIPPER_VERSION=0.41.0

zaheerkhalil321 commented 4 years ago

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:

chrisglein commented 4 years ago

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.

grabbou commented 4 years ago

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.

alexpoon2000 commented 4 years ago

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

nivas412 commented 4 years ago

Myself also having the same issue. Someone please help us

nivas412 commented 4 years ago
  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.

Guuz commented 4 years ago

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.

leslie846933 commented 4 years ago

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

asim47 commented 4 years ago

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

arminsalcin commented 4 years ago

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',
        });
Danushka50 commented 4 years ago

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.

Hiti3 commented 4 years ago

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?

safaiyeh commented 4 years ago

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

brentvatne commented 4 years ago

@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

sureshhallyali commented 4 years ago

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');
                    }
                };
nivas412 commented 4 years ago

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.

sureshhallyali commented 4 years ago

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

nivas412 commented 4 years ago

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

anthony1110 commented 4 years ago

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

dipeshkoirala21 commented 4 years ago

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

HamaniKhalil commented 4 years ago

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

anthony1110 commented 4 years ago

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.

sureshhallyali commented 4 years ago

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

anthony1110 commented 4 years ago

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

vinifraga commented 4 years ago

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.

ys-sherzad commented 4 years ago

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);
    }
ys-sherzad commented 4 years ago

Has this issue been fixed in 0.63.1 ?

UPDATE: Upgraded to 0.63.2 still, the problem persists

anthony1110 commented 4 years ago

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?

girish54321 commented 4 years ago

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

MayoudP commented 4 years ago

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:


"<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>EntityTooLarge</Code>
<Message>Your proposed upload exceeds the maximum allowed size</Message>
<ProposedSize>2025220</ProposedSize>
<MaxSizeAllowed>2023115</MaxSizeAllowed>
<RequestId>{...}</RequestId>
<HostId>5n+{...}</HostId>
</Error>"
girish54321 commented 4 years ago

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

qam12 commented 4 years ago

Thanks @abumostafa

sureshhallyali commented 4 years ago

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

sureshhallyali commented 4 years ago

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

finally worked in android

fritzfr commented 4 years ago

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

Baterka commented 4 years ago

Does this problem really persist for like 4 months?

MayoudP commented 4 years ago

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

andrekovac commented 4 years ago

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?

Baterka commented 4 years ago

@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

anthony1110 commented 4 years ago

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

andrekovac commented 4 years ago

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

anthony1110 commented 4 years ago

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

fikar46 commented 4 years ago

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%

mshehrozsajjad commented 4 years ago

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)

victor012888 commented 4 years ago

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