How to download file React Native App Android | IOS

If you’re a react native developer then you must know how the files are downloaded in react native. In this blog, you will know how can we download any file (image, pdf, word file, etc) from the URL. Let’s integrate.

Step 1: Install rn-fetch-blob Package

npm i rn-fetch-blob
yarn add rn-fetch-blob

After installing rn-fetch-blob, go to the ios directory and run pod install

Step 2: You need to add Android and ios permission.
Android: Go to AndroidManifest.xml and add the below permissions.

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.CAMERA" />

IOS: Go to info.plist and add these lines of code.

<key>NSDocumentsFolderUsageDescription</key>
<string></string>
<key>NSDownloadsFolderUsageDescription</key>
<string></string>

Step 3: Create a function that downloads the file and stores it in the cache.

import RNFetchBlob from 'rn-fetch-blob';
import {Platform, PermissionsAndroid} from 'react-native';

/// grant permission in android
export const getDownloadPermissionAndroid = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      {
        title: 'File Download Permission',
        message: 'Your permission is required to save Files to your device',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) return true;
  } catch (err) {
    console.log('err', err);
  }
};

export const downloadFile = async url => {
  // Get the app's cache directory
  const {config, fs} = RNFetchBlob;
  const cacheDir = fs.dirs.DownloadDir;

  // Generate a unique filename for the downloaded image
  const filename = url.split('/').pop();
  const imagePath = `${cacheDir}/${filename}`;

  try {
    // Download the file and save it to the cache directory
    const configOptions = Platform.select({
      ios: {
        fileCache: true,
        path: imagePath,
        appendExt: filename.split('.').pop(),
      },
      android: {
        fileCache: true,
        path: imagePath,
        appendExt: filename.split('.').pop(),
        addAndroidDownloads: {
          // Related to the Android only
          useDownloadManager: true,
          notification: true,
          path: imagePath,
          description: 'File',
        },
      },
    });

    const response = await RNFetchBlob.config(configOptions).fetch('GET', url);

    // Return the path to the downloaded file
    return response;
  } catch (error) {
    console.error(error);
    return null;
  }
};

Step 4: In the case of Android. You don’t need to do any extra steps. Calling this function downloads the file and saved it in the download folder. But in the case of IOS, you need to open the file in the preview after saving it in the cache as shown below.

import React from 'react';
import {View, Text, TouchableOpacity, StyleSheet, Platform} from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';
import {downloadFile, getDownloadPermissionAndroid} from './src/Functions';

const App = () => {
  const fileUrl = 'https://www.africau.edu/images/default/sample.pdf';
  return (
    <View>
      <Text style={styles.titleText}>File Download Demo App</Text>
      <Text style={styles.titleText}>{fileUrl}</Text>
      <TouchableOpacity
        style={[styles.btnStyle]}
        onPress={() => {
          if (Platform.OS === 'android') {
            getDownloadPermissionAndroid().then(granted => {
              if (granted) {
                downloadFile(fileUrl);
              }
            });
          } else {
            downloadFile(fileUrl).then(res => {
                RNFetchBlob.ios.previewDocument(res.path());
            });
          }
        }}>
        <Text style={styles.textStyle}>Download</Text>
      </TouchableOpacity>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  titleText: {
    textAlign: 'center',
    marginVertical: 20,
    marginHorizontal: 15,
  },
  textStyle: {
    color: 'white',
    fontSize: 14,
    paddingHorizontal: 25,
  },
  btnStyle: {
    backgroundColor: 'black',
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center',
    borderRadius: 10,
    width: 150,
    height: 40,
  },
});

That’s it. If you have any queries. Please feel free to message us.

I hope, this blog really helped you to fix your issue. if you have any queries or suggestions. You can connect with us through the contact section. We are also available on YouTube. Don’t forget to share and subscribe to us. Thank you for your valuable time. Have a nice day ahead.

Leave a Reply

Your email address will not be published. Required fields are marked *