DEV Community

shyam manek
shyam manek

Posted on

how you can use react-native-fs (rnfs) to download a file in React Native

Step 1: Install the dependency

If you haven't already, install react-native-fs by running the following command:

npm install react-native-fs

Enter fullscreen mode Exit fullscreen mode

Step 2: Link the dependency

Link the react-native-fs package to your project

npx react-native link react-native-fs

Enter fullscreen mode Exit fullscreen mode

Step 3: Download a file

You can use the downloadFile method from react-native-fs to download a file. Here's an example:

import React, { useEffect } from 'react';
import { View, Button } from 'react-native';
import RNFS from 'react-native-fs';

const FileDownloadScreen = () => {
  useEffect(() => {
    // Optional: Delete the file if it exists before downloading
    const filePath = RNFS.DocumentDirectoryPath + '/example.pdf';
    RNFS.unlink(filePath)
      .then(() => {
        console.log('Previous file deleted');
      })
      .catch((err) => {
        console.log(err.message);
      });
  }, []);

  const downloadFile = () => {
    const url = 'https://www.example.com/example.pdf';
    const filePath = RNFS.DocumentDirectoryPath + '/example.pdf';

    RNFS.downloadFile({
      fromUrl: url,
      toFile: filePath,
      background: true, // Enable downloading in the background (iOS only)
      discretionary: true, // Allow the OS to control the timing and speed (iOS only)
      progress: (res) => {
        // Handle download progress updates if needed
        const progress = (res.bytesWritten / res.contentLength) * 100;
        console.log(`Progress: ${progress.toFixed(2)}%`);
      },
    })
      .promise.then((response) => {
        console.log('File downloaded!', response);
      })
      .catch((err) => {
        console.log('Download error:', err);
      });
  };

  return (
    <View>
      <Button title="Download File" onPress={downloadFile} />
    </View>
  );
};

export default FileDownloadScreen;

Enter fullscreen mode Exit fullscreen mode

In this example, we first delete any existing file with the same name (example.pdf) if it exists. Then, when the "Download File" button is pressed, the downloadFile function is called. It uses RNFS.downloadFile to initiate the download process. The fromUrl property specifies the URL of the file to download, and the toFile property specifies the path where the downloaded file will be saved.

You can also track the download progress by providing a progress callback to the RNFS.downloadFile method. The callback receives an object with the bytesWritten and contentLength properties, which can be used to calculate and display the download progress.

Remember to replace 'https://www.example.com/example.pdf' with the actual URL of the file you want to download.

That's it! With this example, you can download files using react-native-fs in your React Native app.

Top comments (3)

Collapse
 
benndip profile image
Benndip

Thank you very much for this!!!

Please is it possible to pause and resume the download ?

Collapse
 
calumnias2222 profile image
dslslerjglijsl

WOWOWOWOOWOWOOWOWOWOOW