How can I download a file in react-native? - react-native

I ran this command in my console npm install react-native-fs --save
then have this code in my onclick function
_download = (downloadpath) => {
// console.log(introduction);
var RNFS = require('react-native-fs');
try {
RNFS.downloadFile({
fromUrl: downloadpath,
toFile: `${RNFS.DocumentDirectoryPath}/test.zip`,
}).promise.then((r) => {
this.setState({ isDone: true })
});
} catch (error) {
console.log(error);
// Error saving data
}
}
but its giving this

Well, unfortunately RNFS is not compatible with expo since it wraps native libraries. You can check it out usually in http://native.directory

Related

how to download a file from server

i am working with react native project i have a task to doawnload files and store them in local so use RNFS but i have links like this .../api/v1/files/5e6f831588b03d4ba3d9f69c/download where i use it in chrome it start the download but with in react native it didn't download anything
here is my code
const localFile = `${RNFS.DocumentDirectoryPath}/test2.pdf`;
const options = {
fromUrl:
'.../api/v1/files/5e6f831588b03d4ba3d9f69c/download', //... means the server base url the link is totaly right
toFile: localFile,
};
RNFS.downloadFile(options)
.promise.then(() => FileViewer.open(localFile))
.then(() => {
// success
})
.catch(error => {
// error
});
}

On running my Code on Android Device I get an error as: Execution failed for task ':rn-fetch-blob:compileDebugJavaWithJavac'

I am using the rn-fetch-blob package to download files from url. But on running the code, on android it throws an error as: Execution failed for task ':rn-fetch-blob:compileDebugJavaWithJavac'.
In terminal: Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
This is my code:
import React, { Component } from "react";
import {
View,
Text,
Button,
Alert,
ProgressBarAndroid,
ToastAndroid,
PermissionsAndroid
} from "react-native";
import RNFetchBlob from "rn-fetch-blob";
export default class componentName extends Component {
constructor(props) {
super(props);
this.state = {
progress: 0,
loading: false
};
}
actualDownload = () => {
this.setState({
progress: 0,
loading: true
});
let dirs = RNFetchBlob.fs.dirs;
RNFetchBlob.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
path: dirs.DownloadDir + "/path-to-file.png",
fileCache: true
})
.fetch(
"GET",
"http://www.usa-essays.com/blog/wp-content/uploads/2017/09/sample-5-1024x768.jpg",
{
//some headers ..
}
)
.progress((received, total) => {
console.log("progress", received / total);
this.setState({ progress: received / total });
})
.then(res => {
this.setState({
progress: 100,
loading: false
});
ToastAndroid.showWithGravity(
"Your file has been downloaded to downloads folder!",
ToastAndroid.SHORT,
ToastAndroid.BOTTOM
);
});
};
async downloadFile() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: "Storage Permission",
message: "App needs access to memory to download the file "
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.actualDownload();
} else {
Alert.alert(
"Permission Denied!",
"You need to give storage permission to download the file"
);
}
} catch (err) {
console.warn(err);
}
}
render() {
return (
<View>
<Text> Download Files in Android </Text>
<Button onPress={() => this.downloadFile()} title="Download" />
{this.state.loading ? (
<ProgressBarAndroid
styleAttr="Large"
indeterminate={false}
progress={this.state.progress}
/>
) : null}
</View>
);
}
}
React native 0.60 brings some breaking changes both to Android and iOS.
For the android part the solution (workaround) is explained here: https://facebook.github.io/react-native/blog/2019/07/03/version-60#androidx-support
1) npm install --save-dev jetifier
2) npx jetify
3) npx react-native run-android
4) npx jetify
You will have to do step 4 everytime you add a new module or reset your node_modules folder.
Let me know if this solved your issue
Using React Native version 0.59.0 and 0.60.0 was breaking through and giving errors linked to libraries.
Workout: React Native 0.59.9 Just worked fine.
For the RN 0.60.0, they are giving support for the AndroidX,
You can use the following command to fix this issue.
npm i jetifier
npx jetify
You can refer the following doc for the AndroidX Support.
Ref: https://facebook.github.io/react-native/blog/2019/07/03/version-60
Please go to react-native-fetch-blob/android/build.gradle and update these values
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
to these
compileSdkVersion 26
buildToolsVersion "26.0.3"
defaultConfig {
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName "1.0"
}

how to create pdf in react-native

I want to create pdf in my app in react-native for word to pdf or html to pdf converter.I have tried all possible react-native packages but none of them give me a desired result what should I do.
Are you using nodeJS on the server? If you are, send the html to the server and use this to convert the html to a pdf.
Have you Checked react-native-pdf-lib.
It is pretty good module.
Otherwise consider server side rendering
You can generate pdf file in react native with the npm package react-native-html-to-pdf.
Steps :
Create HTML template of your pdf file you want to generate.
Install the package and install pod in ios folder with pod install
Rebuild the app in android/ios.
import RNHTMLtoPDF from 'react-native-html-to-pdf';
const createPdf = async () => {
try {
let options = {
html: '<div>Hello pdf</div>',
fileName: 'demofile',
directory: 'Downloads',
base64: true,
};
let file = await RNHTMLtoPDF.convert(options);
console.log(file);
} catch (error) {
console.log(error);
}
}
Here is the more specific answer to your problem :
import RNHTMLtoPDF from 'react-native-html-to-pdf';
const createPdf = async () => {
let h1 = "Hey Heading 1";
let h2 = "heading 2";
let para = "Something description";
// use Backtick(`) to define html for your custom dynamic content
const pdf_html = `<div>
<h1>{h1}</h1>
<h1>{h2}</h1>
<h1>{para}</h1>
</div`;
try {
let options = {
html: pdf_html,
fileName: 'demofile',
directory: 'Downloads',
base64: true,
};
let file = await RNHTMLtoPDF.convert(options);
console.log(file);
} catch (error) {
console.log(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.

Download using jsPDF on a mobile devices

I have a page that includes a download button using jsPDF. On desktop machines it downloads the page as it should. However, pdf.save() does not work on my tablet or phone.
I tried to add a special case for mobile devices to open the PDF in a new window, since mobile devices don't download things the same as desktops, with the idea being that once the PDF is open in a new window the user can choose to save it manually.
var pdf = new jsPDF('p', 'pt', 'letter');
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
html2canvas($("#pdf-area"), {
onrendered: function (canvas) {
$("#pdf-canvas").append(canvas);
$("#pdf-canvas canvas").css("padding", "20px");
}
});
var options = {
pagesplit: true
};
function download(doctitle) {
pdf.addHTML($("#pdf-area")[0], options, function () {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
pdf.output('dataurlnewwindow');
} else {
pdf.save(doctitle);
}
});
}
But the download function still does nothing on my tablet/phone. I tested it with this to make sure the pdf.output() function was working:
pdf.addHTML($("#pdf-area")[0], options, function () {
pdf.output('dataurlnewwindow');
});
and it does still work on desktop, but does nothing on mobile.
jsPDF won't download files on mobile apps by this pdf.save(). I have tried and searched for this issue but could not find a complete solution in one place. I am using the file and file-opener plugin. I have developed the solution in Ionic React. Install below modules.
npm i jspdf
npm install cordova-plugin-file
npm install #ionic-native/file
npm install cordova-plugin-file-opener2
npm install #ionic-native/file-opener
ionic cap sync
Go to your file and add these import statements.
import { jsPDF } from "jspdf";
import 'jspdf-autotable';
import { FileOpener } from '#ionic-native/file-opener;
import { File } from '#ionic-native/file';
import { isPlatform } from "#ionic/react";
Check the pdfDownload function
const pdfDownload = async () => {
var doc = new jsPDF();
doc.setFontSize(40);
doc.text("Example jsPDF", 35, 25)
let pdfOutput = doc.output();
if (isPlatform("android")) {
// for Android device
const directory = File.externalRootDirectory + 'Download/';
const fileName = `invoice-${new Date().getTime()}.pdf`
File.writeFile(directory, fileName, pdfOutput, true).then(succ => {
FileOpener.showOpenWithDialog(directory + fileName, 'application/pdf')
.then(() => console.log('File opened'))
.catch(error => console.log('Error opening file', error));
},
err => {
console.log(" writing File error : ", err)
})
} else if (isPlatform("ios")) {
// for iOS device
console.log('ios device')
const directory = File.tempDirectory;
const fileName = `invoice-${new Date().getTime()}.pdf`
File.writeFile(directory, fileName, pdfOutput, true).then(success => {
FileOpener.showOpenWithDialog(directory + fileName, 'application/pdf')
.then(() => console.log('File opened'))
.catch(e => console.log('Error opening file', e));
},
err => {
console.log(" writing File error : ", err)
})
} else {
// for desktop
doc.save("invoice.pdf");
}
}
I had similar issue.
jsPDF won't download file on phones/ tablets / ipads using "pdf.save()".
Do it through File plugin if you are using cordova/phonegap, this will save pdf file in downloads folder (Android) - for the ios you can access pdf file through a path (which is saved somewhere in temp directory) and can send or share.
Hope this helps you.
Here is the solution of download on mobile with jspdf
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
{
var blob = pdf.output();
window.open(URL.createObjectURL(blob));
}
else
{
pdf.save('filename.pdf');
}
Here is the example if you're using the Cordova platform for your development:
https://github.com/saharcasm/Cordova-jsPDF-Email
The workaround of the pdf not being downloaded in the devices is to use cordova-plugin-file.
Use the output method on the doc that will give you the raw pdf which needs to be written & saved in a file.
For example,
var doc = new JsPDF();
//... some work with the object
var pdfOutput = doc.output("blob"); //returns the raw object of the pdf file
The pdfOutput is then written on an actual file by using the file plugin.
The easiest way which works on both Desktop and Mobile is to use:
window.open(doc.output("bloburl"), "_blank");