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
});
}
Related
I am a newbie to React Native myself.
My requirement is to be able to list a set of files that are stored inside the ./assets/ directory. This directory has child directories inside, which then have .mp3 files inside them. I need to extract them as items into a list (ex: flatList, etc).
I am using Expo v46 with React Native v0.69.4, and testing out on iOS simulator.
I tried with this:
import { soundAssets } from '../../assets/sounds_library/sounds_first';
const loadAssets = async () =>
await Promise.all(
soundAssets.map(sound => Asset.fromModule(sound).downloadAsync()),
);
With this, the project does not compile !
The only other way, I found was using 'react-native-fs' but it seems to support only "Pure" React Native. I need to have this project on Expo.
My metro.config.js includes:
resolver: {
assetExts: assetExts.filter(ext => ext !== "svg"),
sourceExts: [...sourceExts, "svg", "cjs", "mp3"]
}};
What is the best way to list out all files inside a folder structure in an assets folder in the application ?
Thank you,
try this
in my case i have assets/www folder
In your app:
const getAllFilePathsFromFolder = async (folderName) => {
const reader = await RNFS.readDirAssets(folderName);
const directories = reader.filter((item) => item.isDirectory());
const files = reader.filter((item) => item.isFile()).map((file) => file.path);
const directioriesFilesPromises = directories.map((dir) => (
getAllFilePathsFromFolder(dir.path)
));
const directioriesFiles = await (await Promise.all(directioriesFilesPromises)).flat(Infinity);
return [...files, ...directioriesFiles];
};
const files = await getAllFilePathsFromFolder('www');
const result = files.filter((filename) => (filename.includes('.mp3')));
result its array of your .mp3 files paths
I'm using this function to load a font with opentype.js in a bare react-native app running on Android, but I'm getting the error "Font could not be loaded" :
const fontLoader = (url) =>
new Promise((resolve, reject) => {
opentype.load('fonts/TextMe-Regular.otf', (error, font) => {
if (error) {
console.log('error on fontLoader:', error);
reject(error);
}
console.log('fontLoader:', font);
resolve(font);
});
});
I've checked the folder inside android > app > src > main > assets > fonts and the TextMe-Regular.otf is there.
My app structure is index.js, App > assets > fonts
EDIT:
I've found a way to load the font from this absolute path:
10.0.2.2:8081/assets/assets/fonts/TextMe-Regular.otf
but I can't find the relative path.
This is my hacky way to dinamically load fonts avoiding Expo.
First of all I linked my assets folder, then I've installed the RNFS to read
the font files and used the _base64ToArrayBuffer function to provide a buffer for opentype.
const fontLoader = (url) =>
new Promise((resolve, reject) => {
const encodedFont = await RNFS.readFileAssets('fonts/TextMe-Regular.otf')
const bufferedFont = _base64ToArrayBuffer(encodedFont);
const loadedFont = opentype.parse(bufferedFont);
resolve(loadedFont);
});
});
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.
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.
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");