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
- Install a fresh ReactNative app via CLI
- Upload a file to the emulator
- 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)
Links to this issue
Commits related to this issue
- flipper: Upgrade Flipper. See discussion [1], where Greg reported that 7c7271598 introduced an issue where uploading images from the camera was broken on Android. The issue is facebook/react-native#... — committed to chrisbobbe/zulip-mobile by chrisbobbe 4 years ago
- flipper: Upgrade Flipper to 0.39.0. See discussion [1], where Greg reported that 7c7271598 introduced an issue where uploading images from the camera was broken on Android. The issue is facebook/rea... — committed to chrisbobbe/zulip-mobile by chrisbobbe 4 years ago
- flipper: Upgrade Flipper to 0.39.0. See discussion [1] and #4281, where Greg reported that 7c7271598 introduced an issue where uploading images from the camera was broken on Android. The issue is fa... — committed to chrisbobbe/zulip-mobile by chrisbobbe 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
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.xmlAccording to docs
This problem is solved by upgrading Flipper in this file
/yourproject/android/gradle.properties
Line 28See : 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!
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.
Go to
android/gradle.properties
and add this lineYou should have the following lines in your
android/app/build.gradle
: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 postI 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
for u guys if u still having this issue i’ve simple solutions:
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 runyarn android
.fetch
package.json
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}
, })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
toFLIPPER_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 andfileType
variable. Let me know if this works for you.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.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 giveimageUri
value asfile:/user/.../path/to/file.jpg
whereas file picker in iOS would giveimageUri
value asfile:///user/.../path/to/file.jpg
.The solution for the first issue is to use
file://
instead offile:
in theformData
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 fieldtype
. Ex: mime-type for.jpg
file would beimage/jpeg
and for.png
file would beimage/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:
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:
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 .
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.
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.
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.javaI have spent close to 8 hours digging the solution for the error.
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?
This solution worked for me:
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
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.
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!
Updating Flipper to 0.45, solve the problem
Hi, I am still getting the issue in 62.2. Solutions tried
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
toFLIPPER_VERSION=0.52.1
4 - in
android/app/build.gradle
overwrite the current Flipper dependencies toand after all these steps ->
npx react-native run-android
oryarn android
5 - in my post upload request
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 aTypeError: Network request failed
. It happens in Android only, both in debug and release, and both with remote debugging and without. Addingandroid: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.
This works for me
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
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:
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:
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!
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
Same issue, tried everything said here! Still not working!
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
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.
i did same, but still facing same issue. iam using
“react”: “16.13.1”, “react-native”: “0.63.1”,
@abumostafa The solution you provided is effective, but it still does not work for files starting with “file:///”. E.g:
formData.append('files', {uri:'https://xxx.jpg', type:'image/jpeg', name:'test.jpeg' })
formData.append('files', {uri:'file:///xxx.jpg', type:'image/jpeg', name:'test.jpeg' })
My react native version:
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:
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.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
@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 persistsJust 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:
Form data should look like this then:
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 (👍 (💯
It worked pretty well, that solved the problem on android, thank u so much.
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
Thanks, I never tried testing in release build. I’ll try that today.
@Brianop no man
I’m confused. Why are you wanting to close this issue if you only found a workaround and the issue was not fixed?