In this article, we are going to learn about How to Download File in React Native using URL. to do this there are some libraries available like react-native-fetch-blob, react-native-fs, rn-fetch-blob but most of the users using rn-fetch-blob. you can see the graph for usage here
Basically, the rn-fetch-blob is a fork of react-native-fetch-blob & react-native-fs is not maintained by its owner. so it is good to use rn-fetch-blob. let’s start with an example
1. Create a new project
1 |
react-native init ProjectName |
2. Install dependency
1 |
npm install --save rn-fetch-blob |
You can refer GitHub site if any errors with rn-fetch-blob
Check these features of rn-fetch-blob:
- Transfer data directly from/to storage without BASE64 bridging
- File API supports regular files, Asset files, and CameraRoll files
- Native-to-native file manipulation API, reduce JS bridging performance loss
- File stream support for dealing with large file
- Blob, File, XMLHttpRequest polyfills that make the browser-based library available in RN (experimental)
- JSON stream supported base on Oboe.js @jimhigson
3. Import the following components
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Import React Component import React from 'react'; // Import Components import { Text, View, Image, StyleSheet, Platform, TouchableOpacity, PermissionsAndroid, } from 'react-native'; // Import RNFetchBlob for the file download import RNFetchBlob from 'rn-fetch-blob'; |
4. Function to download file
In this function first, we are getting today’s date to add the time suffix in the filename. & getFileExtention is this function to get file extension from URL. this is helpful when you want to download a file from a dynamic URL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
const downloadFile = () => { // Get today's date to add the time suffix in filename let date = new Date(); // File URL which we want to download let FILE_URL = fileUrl; // Function to get extention of the file url let file_ext = getFileExtention(FILE_URL); file_ext = '.' + file_ext[0]; // config: To get response by passing the downloading related options // fs: Root directory path to download const { config, fs } = RNFetchBlob; let RootDir = fs.dirs.PictureDir; let options = { fileCache: true, addAndroidDownloads: { path: RootDir+ '/file_' + Math.floor(date.getTime() + date.getSeconds() / 2) + file_ext, description: 'downloading file...', notification: true, // useDownloadManager works with Android only useDownloadManager: true, }, }; config(options) .fetch('GET', FILE_URL) .then(res => { // Alert after successful downloading console.log('res -> ', JSON.stringify(res)); alert('File Downloaded Successfully.'); }); }; |
Function to get an extension from URL
1 2 3 4 5 |
const getFileExtention = fileUrl => { // To get the file extension return /[.]/.exec(fileUrl) ? /[^.]+$/.exec(fileUrl) : undefined; }; |
5. Android Storage permission
To download a file in Android you need to get storage permission access from the user to do this we have to create a function to get storage permission from user
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Function to check the platform // If Platform is Android then check for permissions. const checkPermission = async () => { if (Platform.OS === 'ios') { downloadFile(); } else { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, { title: 'Storage Permission Required', message: 'Application needs access to your storage to download File', } ); if (granted === PermissionsAndroid.RESULTS.GRANTED) { // Start downloading downloadFile(); console.log('Storage Permission Granted.'); } else { // If permission denied then show alert Alert.alert('Error','Storage Permission Not Granted'); } } catch (err) { // To handle permission related exception console.log("++++"+err); } } }; |
6. Source code
Heres the source code for the download File in React Native
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
// How to Download a File in React Native from any URL https://www.techup.co.in/how-to-download-file-in-react-native-using-url/ // Import React Component import React from 'react'; // Import React native Components import { Text, View, Image, StyleSheet, Platform, TouchableOpacity, PermissionsAndroid, } from 'react-native'; // Import RNFetchBlob for the file download import RNFetchBlob from 'rn-fetch-blob'; const Dashboard = () => { const fileUrl = 'https://www.techup.co.in/wp-content/uploads/2020/01/techup_logo_72-scaled.jpg'; const checkPermission = async () => { // Function to check the platform // If Platform is Android then check for permissions. if (Platform.OS === 'ios') { downloadFile(); } else { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, { title: 'Storage Permission Required', message: 'Application needs access to your storage to download File', } ); if (granted === PermissionsAndroid.RESULTS.GRANTED) { // Start downloading downloadFile(); console.log('Storage Permission Granted.'); } else { // If permission denied then show alert Alert.alert('Error','Storage Permission Not Granted'); } } catch (err) { // To handle permission related exception console.log("++++"+err); } } }; const downloadFile = () => { // Get today's date to add the time suffix in filename let date = new Date(); // File URL which we want to download let FILE_URL = fileUrl; // Function to get extention of the file url let file_ext = getFileExtention(FILE_URL); file_ext = '.' + file_ext[0]; // config: To get response by passing the downloading related options // fs: Root directory path to download const { config, fs } = RNFetchBlob; let RootDir = fs.dirs.PictureDir; let options = { fileCache: true, addAndroidDownloads: { path: RootDir+ '/file_' + Math.floor(date.getTime() + date.getSeconds() / 2) + file_ext, description: 'downloading file...', notification: true, // useDownloadManager works with Android only useDownloadManager: true, }, }; config(options) .fetch('GET', FILE_URL) .then(res => { // Alert after successful downloading console.log('res -> ', JSON.stringify(res)); alert('File Downloaded Successfully.'); }); }; const getFileExtention = fileUrl => { // To get the file extension return /[.]/.exec(fileUrl) ? /[^.]+$/.exec(fileUrl) : undefined; }; return ( <View style={styles.container}> <View style={{ alignItems: 'center' }}> <Text style={{ fontSize: 25, textAlign: 'center' }}> React Native File Download Example </Text> </View> <Image source={{ uri: fileUrl, }} style={{ width: '100%', height: 100, resizeMode: 'contain', margin: 5 }} /> <TouchableOpacity style={styles.button} onPress={checkPermission}> <Text style={styles.text}> Download File </Text> </TouchableOpacity> </View> ); }; export default Dashboard; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#FFFFFF', }, text: { color: '#fff', fontSize: 20, textAlign: 'center', padding: 5, }, button: { width: '80%', padding: 10, backgroundColor: 'blue', margin: 10, }, }); |
7. Output:
I have posted another article for rn-fetch-blob iOS implementation. please check this post.