Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to upload image file on first try getting TypeError: Network Request Failed #32966

Closed
ws8149 opened this issue Jan 25, 2022 · 21 comments
Closed
Labels
Component: Image Needs: Triage 🔍 Stale There has been a lack of activity on this issue and it may be closed soon.

Comments

@ws8149
Copy link

ws8149 commented Jan 25, 2022

Description

This issue only occurs on Android devices after updating React Native from v0.63.4 to v0.65.1. For some strange reason, the first attempt at uploading a image file will immediately fail with the error TypeError: Network Request Failed.

If it does fail on the first try, the second or third will succeed. Does anyone know why does this happen or how I can investigate this further? Sometimes this issue does not even happen at all.

Version

0.65.1

Output of npx react-native info

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/react-native-info - Not found
npm ERR! 404
npm ERR! 404 'react-native-info@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\ws8149\AppData\Roaming\npm-cache_logs\2022-01-25T12_34_29_576Z-debug.log
Install for [ 'react-native-info@latest' ] failed with code 1

Steps to reproduce

  1. Use an Android device
  2. Perform an image file upload

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

const handleUpload = async (file) => {
    const form = new FormData()

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

    const token = await getItem(storageKey.token)

     let req_headers = {
       'Content-Type': 'multipart/form-data',
      'Accept': 'application/json',
       Authorization: `Bearer ${token}`,       
     };     

     fetch(`${API_URL}/upload`, {
      method: 'POST',
      body: form,
      headers: req_headers
    })
      .then((response) => response.json())
      .then((response) => {
        console.log('response', response);
      })
      .catch((error) => {
        console.log('error', error);       
      });
     
   };
@Bravo-Lin
Copy link

Maybe you can try to close your browser devtool , somtimes it will block the upload request

@ws8149
Copy link
Author

ws8149 commented Feb 7, 2022

Thanks but its also occurring on release builds

@ws8149
Copy link
Author

ws8149 commented Mar 18, 2022

This problem also occurs on a fresh clean react native project.

The dependencies used in the new project were

"axios": "0.19.2",

"react": "17.0.2",

"react-native": "0.67.4",

"react-native-image-picker": "3.4.0"

The code used was:

        const instance = axios.create({
          baseURL: ENV.API_URL,
          timeout: 10000,
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
            'X-AUTH-TOKEN': 'token',
            'Authorization': 'Bearer ${token}'
          },
        })

       const options = {
          quality: 0.6,
          mediaType: 'photo',
          maxWidth: 500,
          maxHeight: 500,
        }

        launchImageLibrary(options, async (file) => {
          
          const form = new FormData()

          const my_file = {
            uri: file.uri, type: file.type, name: file.fileName
          }

          form.append('file', my_file)

          await instance({                
            method: 'post',
            url: '/upload',
            data: form,          
            headers: {
              'Content-Type': 'multipart/form-data'
            },       
          }).then((res) => {
            console.log(res.data)    
            Alert.alert('TEST', 'UPLOAD SUCCESS')            
          }).catch((err) => {
            console.log(err)
            Alert.alert('TEST', 'UPLOAD FAILED')            
          })
        })

The error shown in the logs were
2022-03-17 10:52:00.969 I/ReactNativeJS: 'err: ', { [Error: Network Error] request: { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4, readyState: 4, status: 0, timeout: 10000, withCredentials: true, upload: {}, _aborted: false, _hasError: true, _method: 'POST', _response: 'Stream Closed',

Does anyone know why the stream closes immediately on the first try?

@zgj0303
Copy link

zgj0303 commented Mar 28, 2022

"react-native": "0.65.1", Having the same problem as you ,did you solve it?

@ws8149
Copy link
Author

ws8149 commented Mar 29, 2022

No, I'm still having the same issue unfortunately.

@font-ds
Copy link

font-ds commented Jun 5, 2022

I solve this problem by using rn-fetch-blob.

@ishaqashraf
Copy link

add 'Content-Type': 'multipart/form-data' in your headers will resolve the issue

@GaylordP
Copy link

Hello,

I have exactly the same problem with [email protected] and [email protected], have you found a solution ?

Thanks :)

@Killyannoor
Copy link

@GaylordP Hey, we're experiencing this same issue. Have you found a way to resolve this yet?

@Arek1020
Copy link

Hi,
any solutions? I have this same issue on android.

@Killyannoor
Copy link

@Arek1020 In my case, downgrading Axios worked. I downgraded to 0.24.0

@anikettari
Copy link

Same issue ! PLEASE HELP

@GeorgeFlorian
Copy link

This worked for me on EXPO SDK 49:
I've installed expo-build-properties using npx expo install expo-build-properties and then added it as a plugin in app.json:

    "plugins": [
      [
        "expo-build-properties",
        {
          "android": {
            "usesCleartextTraffic": true
          }
        }
      ]
    ]

@theharshkonda
Copy link

This worked for me on EXPO SDK 49: I've installed expo-build-properties using npx expo install expo-build-properties and then added it as a plugin in app.json:

    "plugins": [
      [
        "expo-build-properties",
        {
          "android": {
            "usesCleartextTraffic": true
          }
        }
      ]
    ]

not working for cli

@notDemian
Copy link

any solution so far??

@MetriciRO
Copy link

any solution so far??

This one worked for me: #32966 (comment)

Copy link

This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 7 days.

@github-actions github-actions bot added the Stale There has been a lack of activity on this issue and it may be closed soon. label Apr 27, 2024
Copy link

github-actions bot commented May 4, 2024

This issue was closed because it has been stalled for 7 days with no activity.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale May 4, 2024
@avinash-nimblechapps
Copy link

avinash-nimblechapps commented Aug 13, 2024

i have the same issue in IOS and Android both! :)
Any solution ?

@User-DK
Copy link

User-DK commented Nov 6, 2024

So basically one takeaway is pass the image as base64 and json.stringify it to pass it to the endpoint and it worked for me

const handleTakePhoto = async () => {
    if (cameraRef.current) {
      const options = {
        quality: 1,
        base64: true,
      };
      const takedPhoto = await cameraRef.current.takePictureAsync(options);
      if (takedPhoto) {
        const source = takedPhoto.base64;
        if (source) {
          await handleImageUpload(source);
        }
      }
    }
  };

const handleImageUpload = async (source: string): Promise<void> => {
    let base64Img = `data:image/jpg;base64,${source}`;
    const data: ImageUploadData = {
      file: base64Img,
    };

      const response = await fetch(
        "",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        }
      );

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component: Image Needs: Triage 🔍 Stale There has been a lack of activity on this issue and it may be closed soon.
Projects
None yet
Development

No branches or pull requests