Skip to content

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

Closed

Description

@abumostafa

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]

Activity

  1. carlezzo commented on Apr 6, 2020

    @carlezzo

    Same problem here!

  2. adityamohta commented on Apr 6, 2020

    @adityamohta

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

  3. HaidarZ commented on Apr 6, 2020

    @HaidarZ

    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.

  4. adityamohta commented on Apr 6, 2020

    @adityamohta

    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.

  5. adityamohta commented on Apr 6, 2020

    @adityamohta

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

  6. HaidarZ commented on Apr 6, 2020

    @HaidarZ

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

  7. MateuszRostkowski commented on Apr 7, 2020

    @MateuszRostkowski

    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

  8. adityamohta commented on Apr 7, 2020

    @adityamohta

    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.

  9. preko96 commented on Apr 7, 2020

    @preko96

    Same happens here!

  10. alfianwahid commented on Apr 7, 2020

    @alfianwahid

    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

  11. trglairnarra commented on Apr 8, 2020

    @trglairnarra

    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.

  12. abumostafa commented on Apr 8, 2020

    @abumostafa
    Author

    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

  13. safaiyeh commented on Apr 8, 2020

    @safaiyeh
    Contributor

    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.

  14. 303 remaining items

  15. tohshine commented on Jul 16, 2021

    @tohshine

    same issue I have tried all the solutions but doesn't work
    "react-native": "0.64.1",

    while the file is part of the append throws a network error

    ` let body = new FormData()
    body.append('location', 'GOOGLE_DRIVE')
    body.append('docType', 'MEANS_OF_IDENTIFICATION')
    body.append('file', { ...attachment.file })
    const data = await axios.post('/file/api/v1/storage/folder/file', body, config, {
    onUploadProgress: (progress) => {
    const { loaded, total } = progress;
    const percentagProgress = Math.floor((loaded / total) * 100);

                    /* dispatching peercentage */
                    dispatch(fileUploadProgress(attachment.id, percentagProgress));
                },
            });
            /* dispatch success upload */
            dispatch(successFileUpload(attachment.id));
            console.log('success data', data);`
    
  16. itajenglish commented on Jul 16, 2021

    @itajenglish

    Can you guys update your comments with the code you're trying to execute.

  17. thanhhai16 commented on Jul 16, 2021

    @thanhhai16

    Can you guys please help me, I'm struggling with this, I tried all the way, but my code still sends [object Object] to server?
    This was worked well in past at 0.59 .
    Please help me

  18. itajenglish commented on Jul 16, 2021

    @itajenglish

    same issue I have tried all the solutions but doesn't work
    "react-native": "0.64.1",

    while the file is part of the append throws a network error

    ` let body = new FormData()
    body.append('location', 'GOOGLE_DRIVE')
    body.append('docType', 'MEANS_OF_IDENTIFICATION')
    body.append('file', { ...attachment.file })
    const data = await axios.post('/file/api/v1/storage/folder/file', body, config, {
    onUploadProgress: (progress) => {
    const { loaded, total } = progress;
    const percentagProgress = Math.floor((loaded / total) * 100);

                    /* dispatching peercentage */
                    dispatch(fileUploadProgress(attachment.id, percentagProgress));
                },
            });
            /* dispatch success upload */
            dispatch(successFileUpload(attachment.id));
            console.log('success data', data);`
    

    What file is this logic in? Is it in the file with the component that's selecting the image from the file system or a separate file? @tohshine

  19. itajenglish commented on Jul 16, 2021

    @itajenglish

    Can you guys please help me, I'm struggling with this, I tried all the way, but my code still sends [object Object] to server?
    This was worked well in past at 0.59 .
    Please help me

    Update the comment with your RN code @thanhhai16

  20. ionbaratol commented on Jul 21, 2021

    @ionbaratol

    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,
                })
    
  21. FratilaRuxandra commented on Aug 8, 2021

    @FratilaRuxandra

    Check first if your upload works with very small files ( for example, instead of uploading a video, upload a gif ). In my case, any file over 1 MB would return "TypeError: Network request failed".

    After many attemps, it turns out that the problem was caused by me using localtunnel, which limited my maximum file size.

  22. Qazafi-Dev commented on Sep 1, 2021

    @Qazafi-Dev

    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

  23. princefishthrower commented on Sep 13, 2021

    @princefishthrower

    @abumostafa - legend.

    Two weeks. Two weeks of scratching my head why file uploads were working absolutely fine in iOS, but wouldn't work in Android. Commenting a single line in a dev-only relevant file makes it work.

    Incredible.

    I love my life.

  24. skywalker2013 commented on Sep 16, 2021

    @skywalker2013

    i face same issue in RN 0.65.1. why close the issue? have any solution?

  25. juggernauts commented on Sep 29, 2021

    @juggernauts

    @abumostafa - legend.

    Two weeks. Two weeks of scratching my head why file uploads were working absolutely fine in Android, but wouldn't work in iOS. Commenting a single line in a dev-only relevant file makes it work.

    Incredible.

    I love my life.

    @princefishthrower - @abumostafa solution works for Android, how did you manage to resolve it for iOS? We are also facing this issue in iOS

  26. princefishthrower commented on Sep 30, 2021

    @princefishthrower

    @juggernauts In my case the file upload endpoint (sendbird chat profile upload if it helps) was working on iOS well before I did this "fix". To help further, I use the react-native-image-crop-picker with iOS and send the following fields in my 'file':

    const result = await ImagePicker.openPicker(imagePickerOptions);
    const file = {
              uri: result.path,
              type: result.mime,
              name: "anyStringHoweveryouWantToDefineTheFileName",
    };

    Also, I had a huge typo in my comment, this fixed file uploads for Android - iOS was working the whole time. Sorry for any confusion that may have caused! The good news is if you have Android working, iOS should be easier - at least that's how it was in my case.

  27. Commaando commented on Oct 1, 2021

    @Commaando

    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.

    Every Time.even in rn 0.65

  28. locked as resolved and limited conversation to collaborators on Oct 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions