wkh237 / react-native-fetch-blob Goto Github PK
View Code? Open in Web Editor NEWA project committed to making file access and data transfer easier, efficient for React Native developers.
License: MIT License
A project committed to making file access and data transfer easier, efficient for React Native developers.
License: MIT License
When app turned into background, HTTP connections will be interrupt. This would be a problem when transmitting large data.
Reference #51 , we should update rnpm script so that the installation could be easier.
Hello!
This error appears at start launch in the simulator/device.
In my example I'm trying implement this part of code, how we can avoid this issue?
Thank you in advance.
componentDidMount() { RNFetchBlob .config({ // add this option that makes response data to be stored as a file, // this is much more performant. fileCache : true, }) .fetch('GET', 'https://homepages.cae.wisc.edu/~ece533/images/mountain.png') .then((res) => { // the temp file path console.log('The file saved to ', res.path('/')) }) requestPermission("android.permission.ACCESS_FINE_LOCATION").then((result) => { console.log("Granted!", result);// now you can set the listenner to watch the user geo location }, (result) => { console.log("Not Granted!"); console.log(result); });
[email protected]
[email protected]
[email protected]
[email protected]
Relate to #18
I use fetch to post a base64 image data and always go into error in debug or release. when i open debug js, it success. what's wrong. is it anything i have to setting?
Hi. I tried to use your library and get a problem if the site uses self signed certificate. Do you have any solution for that?
Download Manager provides better UX for Android users, we should add support for this.
Also, download file using download manager can avoid problems when app is in suspended.
Are you sure this works? As in my case it doesn't seem to enter in the functions and jumps directly to .then()/.catch(). It waited for the file to upload but never executed anything inside the .progress().
Or may be you could provide an example(point me to it) on how to use it.
Btw, thanks, I'm new to RN and iOS, when nothing else seemed to work, rnfb worked well.
here:
trySendingImageToServer(url,base64ImageString,tryNum){
RNFetchBlob.fetch('POST',url,{
'Authorization' : 'Basic YWRtaW46MXEydzNlNHIlVA==',
},base64ImageString)
.progress((received,total)=>{
console.log('progress',received/total);
})
.then((resp)=>{
console.log("Response : ",resp.text());
})
.catch((err)=>{
console.log("Error : ",err);
if (tryNum>0){
this.trySendingImageToServer(url,base64ImageString,tryNum-1);
console.log("Trying again.. "+tryNum);
}
else{
console.log("Not trying anymore");
Alert.alert('Please check your connection');
}
});
}
Relate to #18
Refer to #58 , since the module uses ES6 style export, developers who uses require('react-native-fetch-blob')
will not be able to use the module directly. Though they can still uses by using default
property, but it would be better if the module can be used more easily.
Hi,
I want to use your package for fetching network images.
The images are protected by Basic Auth.
I would like to use them in an component, but keep getting following error on RNFetchBlob.fetch():
TypeError: Cannot read property 'fetchBlob' of undefined
I'm on RN ^0.22.2
i've installed rnpm and ran the rnpm link
command
Any clue on what i'm missing here?
I download mp3 files from a remote source with react-native-fetch-blob and store them in local filesystem with react-native-fs.
However, the data is stored in base64 encoded then.
Is it possible to store the files directly in its binary format on local storage that i can play these files with this library react-native-sound? Or is there another way?
When response is a file path, we should be able to access the file by using the response object directly, such as
RNFetchBlob
.config({fileCache : true})
.fetch('GET', THE_URL).then((resp) => {
resp.readFile(ENCODING)
resp.writeFile(data, APPEND_OR_REPLACE)
resp.unlink(data, APPEND_OR_REPLACE)
resp.stat(data, APPEND_OR_REPLACE)
})
Header is an optional argument, this is a bug.
Hi guys,
I'm using this library to download a massive amount of separate files to disk (1k+ per load). It's a mapping application, and so this is necessary.
Since the latest version (I upgraded from 0.4.2 to 0.5.2) downloads have slowed down significantly. Any suggestions where I can look to fix this? It almost seems like the requests are now syncrhonous instead of asynchronous. Unable to perform multiple requests at the same time?
Thanks!
IOS supports both upload and download progress, but there's only one way to register progress event handler, this will cause unexpected progress event triggering on IOS.
0.7.0
React-Native implements fetch
API using OKHTTP, we should consider use it.
TODOs
v0.5.0 features are almost finished, before it release we still got something to do.
It's unclear from the docs whether or not this library can be used to upload images from an iOS user's camera roll. The React Native camera roll API returns file URIs like, assets-library://asset/asset.JPG?id=1234-5678-ABCDE-3210&ext=JPG
. Should I be able to use RNFetchBlob.wrap()
on such a URI, like:
RNFetchBlob.fetch('POST', 'http://www.example.com/upload-form', {
Authorization : "Bearer access-token",
'Content-Type' : 'multipart/form-data',
}, [
// append field data from file path
{
name : 'avatar',
filename : 'avatar.png',
data: RNFetchBlob.wrap("assets-library://asset/asset.JPG?id=1234-5678-ABCDE-3210&ext=JPG")
}
...
I'm getting the error:
sorry, the request failed. Please try again. {line: 381, column: 882, sourceURL: file: //index.android.bundle.
Not really sure what the error is all about but it seems I do not get this error when I enable chrome debugging. I tried creating a deploy version of the app in hopes that it would work but it didn't.
I'll come back later to update and provide more info.
Consider the following scenario
If we wish to concat two files or replace content of one file by another, we have to cache the file content in JS context and then write the data to destination.
const fs = RNFetchBlob.fs
fs.readFile(FILE_SRC, 'base64')
.then((b64data) => fs.appendFile(FILE_DEST, b64data, 'base64'))
.then(() => { console.log(`concated ${FILE_SRC} to ${FILE_DEST}`) })
This seems not efficient especially when the file is big, that cache will likely consume up the available memory.
Therefore, I think we should make writeStream
, writeFile
, and appendFile
accept a file path as their input, and then we can do as follow.
const fs = RNFetchBlob.fs
fs.appendFile(FILE_DEST, FILE_SRC, 'uri')
.then(() => { console.log(`concated ${FILE_SRC} to ${FILE_DEST}`) })
uri
encoding type to writeFile
uri
encoding type to appendFile
Most of Android devices have "Downloads" app for users checking files they downloaded. But files downloaded by our API are not visible in "Downloads" app, we have to add support to this.
RNFetchBlobNetwork.m:32:13: ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute
RNFetchBlobNetwork.m:35:13: ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute
RNFetchBlobNetwork.m:36:13: ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute
RNFetchBlobFS.h:18:28: Existing instance variable 'callback' for property 'callback' with unsafe_unretained attribute must be __unsafe_unretained
I'm using 0.5.3.
Is it because I've added the project manually rather then with rnpm and have missed some build flags?
Hi,
Android 23 runs with runtime permissions, so if you want to write to the downloads folder for example you don't just state that in the manifest file, you also have to have a runtime check and confirmation from the user.
https://developer.android.com/training/permissions/requesting.html
I can't see that how this has been implemented in this module, if it hasn't due to being outside of scope / requirements then does anyone have any advice on how to apply this. Due to the nature of the module here I would think it would be very useful to add to the Read me.
Thanks
Hi @wkh237, awesome library, much needed in React Native.
My suggestion is:
Let me know if you will pursue such a change, in any case I'll take a look at the code and see if I can come up with something (at least on the Android side)
RNFetchBlob.fetch('GET', mediaUrl, {})
A promise is returned but .then() or .catch() will never being reached because of an exception:
undefined is not an object (evaluating 'RNFetchBlob[nativeMethodName]')
(tested in an iOS-project)
In upcoming version v0.5.0, new APIs allow RN app access file system directly, is there a better solution to remove cached files than just manually calling unlink
API ?
The README.md has to much content, I think it would be better to leave recipes in README.md and move API references to wiki.
When post/put multipar/form-data
with android, the file extension is missing in request body.
I had a case when working with an API where I needed to specifically set the Content-Type (from "application/octet-stream" to "image/jpeg". As a quick hack, I implemented it this way [on the feat_45 branch]:
diff --git a/src/ios/RNFetchBlobReqBuilder.m b/src/ios/RNFetchBlobReqBuilder.m
index df4c3d1..6b44b74 100644
--- a/src/ios/RNFetchBlobReqBuilder.m
+++ b/src/ios/RNFetchBlobReqBuilder.m
@@ -134,6 +134,7 @@
{
NSString * name = [field valueForKey:@"name"];
NSString * content = [field valueForKey:@"data"];
+ NSString * contentType = [field valueForKey:@"type"];
// field is a text field
if([field valueForKey:@"filename"] == nil || content == [NSNull null]) {
[formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
@@ -155,7 +156,7 @@
NSString * filename = [field valueForKey:@"filename"];
[formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename] dataUsingEncoding:NSUTF8StringEncoding]];
- [formData appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
+ [formData appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", contentType] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:content];
[formData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
i++;
@@ -174,7 +175,7 @@
NSString * filename = [field valueForKey:@"filename"];
[formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename] dataUsingEncoding:NSUTF8StringEncoding]];
- [formData appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
+ [formData appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", contentType] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:blobData];
[formData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
..and used it like this:
RNFetchBlob.fetch('POST', url, {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "multipart/form-data",
}, [
{
name: 'image',
filename: filename,
data: RNFetchBlob.wrap(asset.uri),
"type": 'image/jpeg',
},
{
name: "someOtherField",
data: JSON.stringify({foo: 1, bar: 2}),
"type": "application/json",
},
I figured you might want to implement it different so that it's optional, and works on Android, so no PR currently :-)
According to #37 advice from @vaibhawc , perhaps we should consider implement Blob
class on RN since we already have network and fs APIs. This may let some JS libraries that depends on web API becomes available in RN. At least we can try to make firebase.storage work.
These are polyfills that planned to be implemented so far
This feature will develop on branch 0.8.0
The only way to read/write file is using file stream, there should be some handy API make this easier.
for example
fs.readFile(path-to-file).then((data) => {
// ...
})
fs.writeFile(path-to-file).then((data) => {
// ...
})
there will be lot of features in the future, so that current API needs to be extend, but how?
I'm trying to use readStream, but react native is giving me the red-screen-of-death with the message, "_reactNativeFetchBlob2.default.readStream is not a function".
The package was installed using npm
and linked using rnpm
. And ideas?
Versions:
I keep receiving the error “RNFetchBlob.fetch is not a function”.
I put a more detailed description of the error on StackOverflow if anyone cares to take a look. Thanks.
The module now transforms downloaded data into BASE64 string in native context, but it will be inefficient if the developer intend to save the data into storage directly.
Perhaps there should be an option for make it more applicable.
Hey, I'm seeing a strange issue on Android when I try to use this lib.
I'm working on an application that needs to download images from the web, and store them on device. However, as you can see, the process is completed by AsyncHTTP, but the callback itself is never called.
My code:
RNFetchBlob
.config({
fileCache: true,
path : fileName
})
.fetch('GET', tile.url, {})
.then((res) => {
console.log("Saved to " + res.path())
processedTiles++;
if (processedTiles >= tilesToBeProcessed) {
parent.onTileProcessed(card, index);
}
});
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.