How to Download File in React Native

  1. Using the react-native-fs Library
  2. Using the react-native-fetch-blob Library
  3. Conclusion
  4. FAQ
How to Download File in React Native

In the world of mobile app development, React Native has emerged as a popular choice for creating cross-platform applications. One common requirement in many apps is the ability to download files. Whether you’re building a document viewer, a media player, or any app that requires file downloads, knowing how to implement this feature is crucial. This tutorial will guide you through the process of downloading files in React Native, ensuring that you can enhance your app’s functionality seamlessly.

We’ll explore different methods to achieve file downloads, focusing on practical code examples and clear explanations. By the end of this tutorial, you’ll have a solid understanding of how to implement file downloads in your React Native applications. So, let’s dive into the details!

Using the react-native-fs Library

One of the most popular libraries for file system access in React Native is react-native-fs. This library provides a simple and efficient way to download files directly to the device’s file system.

First, you need to install the library. Open your terminal and run the following command:

npm install react-native-fs

After installing, link the library to your project. If you are using React Native 0.60 or higher, the linking is done automatically. If not, you can link it manually:

react-native link react-native-fs

Next, you can implement the file download feature. Here’s a basic example:

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

const DownloadFile = () => {
  const downloadFile = async () => {
    const fileUrl = 'https://example.com/sample.pdf';
    const filePath = `${RNFS.DocumentDirectoryPath}/sample.pdf`;

    try {
      const response = await RNFS.downloadFile({
        fromUrl: fileUrl,
        toFile: filePath,
      }).promise;

      if (response.statusCode === 200) {
        console.log('File downloaded successfully:', filePath);
      } else {
        console.log('Failed to download file:', response.statusCode);
      }
    } catch (error) {
      console.error('Download error:', error);
    }
  };

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

export default DownloadFile;

In this example, we first import the necessary components and the react-native-fs library. The downloadFile function is where the magic happens. We specify the URL of the file we want to download and the path where it will be saved. The RNFS.downloadFile method is called, and we use the promise it returns to handle success and error cases. If the file is downloaded successfully, we log the file path to the console; otherwise, we log an error.

Output:

File downloaded successfully: /data/user/0/com.yourapp/files/sample.pdf

The react-native-fs library is a powerful tool that simplifies file handling in React Native. By using this library, you can easily manage file downloads and access the file system, providing a better user experience in your applications.

Using the react-native-fetch-blob Library

Another option for downloading files in React Native is the react-native-fetch-blob library. This library offers robust features for handling network requests, including file downloads. However, note that react-native-fetch-blob has been deprecated in favor of rn-fetch-blob. Thus, we will use rn-fetch-blob to demonstrate file downloading.

First, install the library:

npm install rn-fetch-blob

Once installed, you can use it to download files. Here’s how you can implement it:

import React from 'react';
import { View, Button } from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';

const DownloadFileWithFetchBlob = () => {
  const downloadFile = () => {
    const fileUrl = 'https://example.com/sample.pdf';
    const filePath = `${RNFetchBlob.fs.dirs.DocumentDir}/sample.pdf`;

    RNFetchBlob.config({
      path: filePath,
    })
      .fetch('GET', fileUrl)
      .then((res) => {
        console.log('File downloaded successfully:', res.path());
      })
      .catch((error) => {
        console.error('Download error:', error);
      });
  };

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

export default DownloadFileWithFetchBlob;

In this code snippet, we again import the necessary components and the rn-fetch-blob library. The downloadFile function specifies the file URL and the desired save path. We then configure the download using RNFetchBlob.config, which allows us to set the file path. The fetch method is called with the HTTP method and the file URL. If the download is successful, we log the file path; otherwise, we catch and log any errors.

Output:

File downloaded successfully: /data/user/0/com.yourapp/files/sample.pdf

Using rn-fetch-blob provides a straightforward way to handle file downloads in React Native. Its configuration options allow for customization, making it a flexible choice for developers looking to implement file downloads in their applications.

Conclusion

Downloading files in React Native is a vital feature that can significantly enhance your app’s functionality. In this tutorial, we explored two powerful libraries, react-native-fs and rn-fetch-blob, that simplify the process of downloading files. By following the examples provided, you can easily implement file downloads in your applications, ensuring a seamless user experience.

Remember to handle errors gracefully and inform users of the download status. With these tools at your disposal, you’re well-equipped to take your React Native applications to the next level. Happy coding!

FAQ

  1. How do I install the necessary libraries for downloading files in React Native?
    You can install the libraries using npm. For react-native-fs, use npm install react-native-fs and for rn-fetch-blob, use npm install rn-fetch-blob.

  2. Can I download files from any URL?
    Yes, you can download files from any publicly accessible URL. Just ensure that the URL is valid and points to a downloadable file.

  3. What file formats can I download using React Native?
    You can download various file formats such as PDFs, images, text files, and more, as long as the file is accessible via a URL.

  4. How can I check if a file has been downloaded successfully?
    You can check the response status code after the download attempt. A status code of 200 typically indicates a successful download.

  5. Is it necessary to handle errors during file downloads?
    Yes, it’s important to handle errors to provide feedback to users and ensure a better user experience.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - React Native