Downloading image file with react native fetch blob - react-native

I am trying to learn react native and how to download files to the device. I know you can do this with react native file system but that does not support authentication which I need. React native fetch blob does support this.
For education purposes, I want to have the code from the first answer to this question recreated in react native fetch blob instead of react native file system.
I someone could write sutch an examlple form me I would be super tankfull.
Question: Downloading data files with React Native for offline use

Try this, it's work fine on Android:
export const download = (url, name) => {
const { config, fs } = RNFetchBlob;
let PictureDir = fs.dirs.PictureDir;
let options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true,
notification: true,
path: PictureDir + name,
description: t('downloading_file')
}
};
config(options)
.fetch('GET', url)
.then(res => {
if (res.data) {
alert(t('download_success'));
} else {
alert(t('download_failed'));
}
});
};

downloadImage(){
var date = new Date();
var url = "http://debasish.com/image.jpg";
var ext = this.getExtention(url);
ext = "."+ext[0];
const { config, fs } = RNFetchBlob ;
let PictureDir = fs.dirs.PictureDir
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true,
notification : true,
path: PictureDir + "/image_"+Math.floor(date.getTime()
+ date.getSeconds() / 2)+ext,
description : 'Image'
}
}
config(options).fetch('GET', url).then((res) => {
Alert.alert("Download Success !");
});
}
getExtention(filename){
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) :
undefined;
}

Related

React Native Share app icon not showing on share sheet

I have set up react-native-share with RN .68.1 and the latest of react-native-share, and everything works great except for the app icon is not showing. The documentation doesn't really explain it very well.
My share code:
const handleShare = (title: string, url: string) => {
const parsedTitle = HtmlTextParser(title);
const shareOptions = Platform.select({
ios: {
title: parsedTitle ?? '',
message: parsedTitle,
url: `https://testUrl.com${url}`,
},
default: {
title: parsedTitle ?? '',
message: parsedTitle,
url: `https://testUrl.com${url}`,
},
});
try {
const share = Share.open({...shareOptions, failOnCancel: false});
} catch (e) {
console.log('error: ', e);
}
};
Can I set a custom icon here easily? Is there a working example somewhere that I can consult to make this happen?

I am converting Images to pdf using a npm library in react native why it is giving error of null object?

I am using react-native-image-to-pdf library to convert images to pdf in my react native app. from https://www.npmjs.com/package/react-native-image-to-pdf
var photoPath = ['https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350','https://images.pexels.com/photos/20787/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350'];
const myAsyncPDFFunction = async () => {
try {
const options = {
imagePaths: photoPath,
name: 'PDFName',
};
const pdf = await RNImageToPdf.createPDFbyImages(options);
console.log(pdf.filePath);
} catch(e) {
console.log(e);
}
}
but this is giving error Error: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
I have also tried giving path as ['./assets/a.png', './assets/b.png']
but still getting same error
Based on the usage example, your photoPath needs to be a local file path and not a remote path.
My recommendation is to first use rn-fetch-blob to download the remote image to the device, and then pass your new local image path to react-native-image-to-pdf. Something like:
RNFetchBlob
.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.png', {
//some headers ..
})
.then(async (res) => {
// the temp file path
console.log('The file saved to ', res.path())
const options = {
imagePaths: [res.path()],
name: 'PDFName',
};
const pdf = await RNImageToPdf.createPDFbyImages(options);
})
from file path remove the text 'file://; with empty string('').
const options = {
imagePaths: [uri.replace('file://', '')],
name: 'FileName',
quality: .9, // optional compression paramter
};
replace('file://', '') it's work for me

how to implement an image and pdf picker in one single upload button in expo?

I am building a mobile app by using EXPO.Now i am stucked in a img & pdf picker,i can't pick image and pdf in one single function or button. can anyone know any packages that enable pdf & image picker in one function.....
You can use expo document picker to pick multiple file types and images as following:
import * as DocumentPicker from 'expo-document-picker';
const picker = await DocumentPicker.getDocumentAsync({
type: "*/*",
multiple: true,
copyToCacheDirectory: true
});
Check the official expo docs DocumentPicker
If you wanna allow your user to select pdf then you can do this
async function openDocumentPicker() {
try {
const res = await DocumentPicker.getDocumentAsync({
type: "*/*",
copyToCacheDirectory: true,
multiple: false,
});
console.log(res)
var lastThree = res.name.substr(res.name.length - 3);
if(lastThree == 'pdf')
{
if(res.type == 'success')
{
//Do Something here
}
}
else
{
alert('Please select PDF File')
}
} catch (error) {
alert(error);
}
}

I am developing react native app, in that i need to support upload files using OneDrive,Dropbox . Is there any way to get it done

I need to pick files from onedrive and dropbox. Is there any npm modules available.
This is an old question, but I ran into the same issue. Spent a while finding the best solution.
Using an in-browser package react-native-inappbrowser and the deepLink functionality. I was able to solve the issue.
You will have to look at the OneDrive/Dropbox documentation for allowing a RedirectUI for a react-native app.
const redirectUrl = 'com.******.*******://auth'
export const tryDeepLinking = async () => {
const loginUrl =
'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
const redirectUrl = getDeepLink();
const url = `${loginUrl}?redirect_url=
${encodeURIComponent(redirectUrl,)}
&client_id=${encodeURIComponent('**********',)}
&response_type=${encodeURIComponent('token')}
&scope=${encodeURIComponent(
'openid Files.ReadWrite.All offline_access',
)}`;
try {
if (await InAppBrowser.isAvailable()) {
const result: any = await InAppBrowser.openAuth(url, redirectUrl, {
// iOS Properties
ephemeralWebSession: false,
// Android Properties
showTitle: false,
enableUrlBarHiding: true,
enableDefaultShare: false,
});
const paramsString = result.url.split('#')[1];
let params: any = {};
paramsString.split('&').forEach(kv => {
const keyValue = kv.split('=', 2);
params[keyValue[0]] = keyValue[1];
});
await setStorageAzureToken(params.access_token);
Alert.alert('Response', 'Success');
} else {
Alert.alert('InAppBrowser is not supported :/');
}
} catch (error) {
console.error(error);
Alert.alert('Something’s wrong with the app :(');
}
};
This is what I am using to get the OneDrive access token, from there you are able to use the https://graph.microsoft.com/v1.0/ api's to manage files.
You can try to use react-native-document-picker.

How to download a file with React Native?

I am building an app with React Native, for Android and iOS. I am trying to let the user download a PDF file when clicking on a button.
react-native-file-download does not support Android
react-native-fs does nothing when I trigger downloadFile (nothing shows up on the notification bar), and I am not able to find the file after that. I added android.permission.WRITE_EXTERNAL_STORAGE to the Android Manifest file. I double-checked that the file I am trying to download exists (when it does not, the library throws an error)
I do not find other solutions for this problem. I have found libraries for viewing a PDF, but I would like to let the user download the PDF.
Just implemented the download feature an hour ago :p
Follow these steps:
a) npm install rn-fetch-blob
b) follow the installation instructions.
b2) if you want to manually install the package without using rnpm, go to their wiki.
c) Finally, that's how I made it possible to download files within my app:
const { config, fs } = RNFetchBlob
let PictureDir = fs.dirs.PictureDir // this is the pictures directory. You can check the available directories in the wiki.
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true, // setting it to true will use the device's native download manager and will be shown in the notification bar.
notification : false,
path: PictureDir + "/me_"+Math.floor(date.getTime() + date.getSeconds() / 2), // this is the path where your downloaded file will live in
description : 'Downloading image.'
}
}
config(options).fetch('GET', "http://www.example.com/example.pdf").then((res) => {
// do some magic here
})
If you're using Expo, react-native-fetch-blob won't work. Use FileSystem.
Here's a working example:
const { uri: localUri } = await FileSystem.downloadAsync(remoteUri, FileSystem.documentDirectory + 'name.ext');
Now you have localUri with the path to the downloaded file. Feel free to set your own filename instead of name.ext.
I Followed the solution from Jonathan Simonney, above on this post. But I had to change it a little:
const { config, fs } = RNFetchBlob;
const date = new Date();
const { DownloadDir } = fs.dirs; // You can check the available directories in the wiki.
const options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true, // true will use native manager and be shown on notification bar.
notification: true,
path: `${DownloadDir}/me_${Math.floor(date.getTime() + date.getSeconds() / 2)}.pdf`,
description: 'Downloading.',
},
};
config(options).fetch('GET', 'http://www.africau.edu/images/default/sample.pdf').then((res) => {
console.log('do some magic in here');
});
GetItem_downloadbtn = (item, itemname) => {
console.log("fiel url comiugn jdd " + item);
console.log("item name checkoing " + itemname);
const android = RNFetchBlob.android;
const filename = itemname;
const filepath = RNFetchBlob.fs.dirs.DownloadDir + '/foldernamae/' + filename;
const downloadAppUrl = item;
RNFetchBlob.config({
addAndroidDownloads: {
useDownloadManager: true,
title: 'great, download success',
description:'an apk that will be download',
mime: 'application/vnd.android.package-archive',
// mime: 'image/jpeg',
// mediaScannable: true,
notification: true,
path: filepath
}
})
.fetch('GET', downloadAppUrl)
.then((res) => {
// console.log('res.path ', res.path());
alert('res.path ', res.path());
android.actionViewIntent(res.path(), 'application/vnd.android.package-archive');
})
.catch((err) => {
alert('download error, err is', JSON.stringify(err));
});
}
I had the same issue, got it working using Expo WebBrowser Module
// install module
npm install react-native-webview
// import the module
import * as WebBrowser from 'expo-web-browser';
// then in your function you can call this function
await WebBrowser.openBrowserAsync(file_ur);
it will open preview of the file and then user can download using share button.