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

react-native 0.63.2 Image upload error [TypeError: Network request failed] #29493

Closed
sureshhallyali opened this issue Jul 25, 2020 · 17 comments
Closed

Comments

@sureshhallyali
Copy link

Description:

When I am trying to post data with fetch() it will post data successfully but if image or any file try to post then it will throw error as shown below
Error : [TypeError: Network request failed]

code:

function openImagePicker() {
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true
})
.then(image => {
console.log(image.path);
const data = new FormData();
data.append('email', "email");
data.append('file', { uri:image.path, name: 'image.jpg', type: 'image/jpeg/jpg'});

                    let res = fetch(
                                  'http://134.209.144.127/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);
                    });
                    
    });

}
Note:

  • Using react-native-image-crop-picker package
  • in android permission also given such as

    android:usesCleartextTraffic="true"
    in this file android/app/src/main/AndroidManifest.xml

React Native version: "react-native": "0.63.2",

Tried this all solution but not working

1 : By giving Permission
uesCleartextTraffic="true" to the AndroidManifest.xml file found inside the dir android/app/src/main/AndroidManifest.xml
for handle http and https

2: Adding comment
// initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
in this file /android/app/src/main/java/com/{your_project}/MainApplication.java
3: Adding comment
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
in his file android/app/src/debug/java/com/{your_project}/ReactNativeFlipper.java

4: By upgrading upgrade react native to 63.2 or new version
5: FLIPPER version upgrading to 50.0

Source image
Screenshot from 2020-07-26 01-19-53

@nhuson269
Copy link

My application needs to solve this problem, I have had an issue with iOS since upgrading to version 0.63.x

#29021

@Mhde96
Copy link

Mhde96 commented Jul 28, 2020

am have same issues with react native 0.63

@sjonchhe
Copy link

I had the same issue in rn v0.62.2. Solved it by upgrading flipper version to 0.47.0

@andrekovac
Copy link

andrekovac commented Jul 31, 2020

@sjonchhe How do you upgrade the Flipper version for iOS?

Did you update it in ios/Podfile in the line versions['Flipper'] ||= '~> 0.51.0'?

However, updating to 0.51.0 (or 0.47.0) all didn't solve it for me...

(For Android I update FLIPPER_VERSION in gradle.properties)

@dharmendrashah
Copy link

dharmendrashah commented Jul 31, 2020

i remember this issue, i spent 4 days to google this thing out but nothing works.
will this is a vey common problem in RN 0.62 and later
But this react-native-fetch-blob package is really good try this it will sure help you out.

@andrekovac
Copy link

andrekovac commented Jul 31, 2020

For me it's an issue because the requests of packages I use (i.e. react-native-video and @aws-amplify/auth) fail..
So I can't just switch to another package..

@ignaciosantise
Copy link

In my case, the problem was Flipper.
This is how i partially solved the problem in Android:

#28551 (comment)

@cbedoy
Copy link

cbedoy commented Aug 3, 2020

Same error here, iOS app work perfectly but Android is failing on 0.62.2, 0.63.0, 0.61...

2020-08-02 23:41:44.331 22868-22964/com.rndagm8 E/unknown:NetworkingModule: Failed to send url request: http://amazing.url.com
    java.lang.IllegalStateException: Multipart body must have at least one part.
        at okhttp3.MultipartBody$Builder.build(MultipartBody.java:341)

I already disabled Flipper and still failing, oh god! I've expending to much time facing error with iOS releasing and now this thing, what's next?

@safaiyeh
Copy link
Contributor

safaiyeh commented Aug 3, 2020

Duplicate of #28551

Let me know if the solutions on that issue help resolve this.

@meiqi1992
Copy link

same issue+1

@premdasvm
Copy link

same issue +1

@sudheepkr
Copy link

sudheepkr commented Sep 27, 2020

Iam using "react-native": "0.63.2"

Error gone i did like this way.
1)Added a comment
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
file path: android/app/src/debug/java/com/{your_project}/ReactNativeFlipper.java
2) Added code in component
let formData = new FormData();
formData.append('file_name', {uri: fileUri,type:fileType,name:fileName});

@Asimurrehman
Copy link

I am also using "react-native": "0.63.2"

my error Gone i did in the same way above :

1)Added a comment
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
file path: android/app/src/debug/java/com/{your_project}/ReactNativeFlipper.java
then Rebuild my App using 'yarn run android '
then every thing will successfully worked

my code 👍

    let body = new FormData();
    body.append('submit', 'ok');
    body.append('file', {
      uri: res.uri,
      name: res.fileName,
      type: res.type,
    });

@phaolin10
Copy link

same issue

@prakhar-mindcrew
Copy link

still getting same, rn version 0.63.4 and FLIPPER_VERSION=0.54.0. please suggest how can i fix ?

@banjo09
Copy link

banjo09 commented May 26, 2021

Doing this:

appending the uri information does not work. It doesn't even send the network request when I try to append an object. But if I append it as a string using Json stringify method.

Then it will send the request, but it breaks for obvious reasons. Why is FormData not allowing me to append an object?

from react-native-image-picker/react-native-image-picker#798 by https://github.com/reboss

@11AA8R4
Copy link

11AA8R4 commented Aug 13, 2021

### Answer
1 - on android, if your 'uri' or 'path' being uploaded is not starting with file:// appearently you wont be uploading your file, so:
2 - try some of these:
a - if(asset.slice(0,7)!=='file://' && Platform.OS==='android') asset = 'file://'+asset // (where 'asset' is your path/uri)
b - or, temporarily upload your image with RNFetchBlob // (i teach you how to later on)
then add the 'file://' in front of your uri/path

### Additional
How to upload localy using RNFetchBlob (if you want):
1 - install the library: rn-fetch-blob
Note: There are additional steps in installation that must be done, like the one to add android:requestLegacyExternalStorage="true"
to your manifest's android file (without this and the other steps you might not being able to store the image)
2 - Then when rn-fetch-blob is properly (and fully) installed, create your file: (replace AAAA with your desired folder inside your phone)

//async function
const res = await DocumentPicker.pick({type:[DocumentPicker.types.allFiles]})
if(res.uri){
  const URI = await RNFetchBlob.fs.readFile(res.uri,'base64')
  const type = (URI.split(':')[1]).split('/')[0]
  const ext = (URI.split(';')[0]).split('/')[1]
  const path = `{RNFetchBlob.fs.dirs.DCIMDir}/AAAA/${fileName}.${ext}`
  await RNFetchBlob.fs.writeFile(path,URI.split(',')[1],'base64')
}

This code will properly Read your file as base64, detected file type, extension, create a path where you desire (this path will be your uri further) and store your image localy on your phone as a base64 image
Finally all you need is to use that path variable inside your formData AS FOLLOWS if android:
'file://'+path

Usage example:

if(path.slice(0,7)!=='file://' && Platform.OS==='android') path = 'file://'+path
formData.append(index,{uri:path,name:'fileName.jpeg',type:'image/jpeg'})

@facebook facebook locked as resolved and limited conversation to collaborators Oct 1, 2021
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Oct 1, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests