How to Download an Image in React Native from any URL

Image Download in React Native

In this post, we will see how to download an Image in React Native from any URL. For this task, I have tried many different libraries and many different ways but found that downloading an image using rn-fetch-blob library is very easy.

While searching the library solution to download the file I found mainly 3 libraries

  1. react-native-fetch-blob
  2. react-native-fs
  3. rn-fetch-blob

But you see react-native-fetch-blob vs react-native-fs vs rn-fetch-blob trend you will see most of the people are using rn-fetch-blob and the reason is

  1. react-native-fs was the first popular file system management library introduced for React native but their original creators are not maintaining the library now, they got changed suddenly and new maintainers are not providing the updates properly
  2. react-native-fetch-blob was the alternate solution that was providing the same features while react-native-fs had no maintainer.
  3. rn-fetch-blob is the fork of react-native-fetch-blob and now the maintainer of react-native-fetch-blob archived the library and suggesting to use rn-fetch-blob because it has more feature and updated as compared to react-native-fetch-blob.

Features of rn-fetch-blob

rn-fetch-blob is a project committed to making file access and data transfer easier, efficient for React Native developers. With the help of this library, you can perform the following task
  • 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

To Download an Image

To download an image using rn-fetch-blob we will use the RNFetchBlob component which provides a fetch method with some different configuration. Here is the code snippet to download the image.

const { config, fs } = RNFetchBlob;
let PictureDir = fs.dirs.PictureDir;
let options = {
  fileCache: true,
  addAndroidDownloads: {
    //Related to the Android only
    useDownloadManager: true,
    notification: true,
    path:
      PictureDir +
      '/image_' +
      Math.floor(date.getTime() +
      date.getSeconds() / 2) + ext,
    description: 'Image',
  },
};
config(options)
  .fetch('GET', image_URL)
  .then(res => {
    //Showing alert after successful downloading
    console.log('res -> ', JSON.stringify(res));
    alert('Image Downloaded Successfully.');
  });

Project Overview

In this example, we will have an Image component that shows the image we are going to download and a button to start downloading process. On click of the button, we will check for the platform

  1. If found Android then we will ask for the permission and once we get the permission we will start downloading the image
  2. If found iOS we will directly start downloading

We will store the downloading image to the default picture directory of the device. I hope you got my point so without any delay let’s see the code.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

As I said we are going to use rn-fetch-blob library for that which needs to be installed in our project and to install this library open the terminal and jump into your project

cd ProjectName

and run the following command

npm install rn-fetch-blob --save

CocoaPods Installation

Now we need to install pods

cd ios && pod install && cd ..

Android Permission to Access Contact List

In this example, we are going to store the downloaded file in the external storage and to do that we have to add permission into the AndroidManifest.xml file. Please add the following permissions in your AndroidMnifest.xml.

Go to YourProject -> android -> app -> main -> AndroidMnifest.xml

<uses-permission
  android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
Permission Purpose
WRITE_EXTERNAL_STORAGE To create any file in external storage

File Download Android Permission
For more about the permission, you can see this post.

Code to Download Image in React Native

Open App.js in any code editor and replace the code with the following code

App.js

// How to Download an Image in React Native from any URL
// https://aboutreact.com/download-image-in-react-native/

// Import React
import React from 'react';

// Import Required Components
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  PermissionsAndroid,
  Image,
  Platform,
} from 'react-native';

// Import RNFetchBlob for the file download
import RNFetchBlob from 'rn-fetch-blob';

const App = () => {
  const REMOTE_IMAGE_PATH =
    'https://raw.githubusercontent.com/AboutReact/sampleresource/master/gift.png'
  const checkPermission = async () => {
    
    // Function to check the platform
    // If iOS then start downloading
    // If Android then ask for permission

    if (Platform.OS === 'ios') {
      downloadImage();
    } else {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'Storage Permission Required',
            message:
              'App needs access to your storage to download Photos',
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          // Once user grant the permission start downloading
          console.log('Storage Permission Granted.');
          downloadImage();
        } else {
          // If permission denied then show alert
          alert('Storage Permission Not Granted');
        }
      } catch (err) {
        // To handle permission related exception
        console.warn(err);
      }
    }
  };

  const downloadImage = () => {
    // Main function to download the image
    
    // To add the time suffix in filename
    let date = new Date();
    // Image URL which we want to download
    let image_URL = REMOTE_IMAGE_PATH;    
    // Getting the extention of the file
    let ext = getExtention(image_URL);
    ext = '.' + ext[0];
    // Get config and fs from RNFetchBlob
    // config: To pass the downloading related options
    // fs: Directory path where we want our image to download
    const { config, fs } = RNFetchBlob;
    let PictureDir = fs.dirs.PictureDir;
    let options = {
      fileCache: true,
      addAndroidDownloads: {
        // Related to the Android only
        useDownloadManager: true,
        notification: true,
        path:
          PictureDir +
          '/image_' + 
          Math.floor(date.getTime() + date.getSeconds() / 2) +
          ext,
        description: 'Image',
      },
    };
    config(options)
      .fetch('GET', image_URL)
      .then(res => {
        // Showing alert after successful downloading
        console.log('res -> ', JSON.stringify(res));
        alert('Image Downloaded Successfully.');
      });
  };

  const getExtention = filename => {
    // To get the file extension
    return /[.]/.exec(filename) ?
             /[^.]+$/.exec(filename) : undefined;
  };

  return (
    <View style={styles.container}>
      <View style={{ alignItems: 'center' }}>
        <Text style={{ fontSize: 30, textAlign: 'center' }}>
          React Native Image Download Example
        </Text>
        <Text
          style={{
            fontSize: 25,
            marginTop: 20,
            marginBottom: 30,
            textAlign: 'center',
          }}>
          www.aboutreact.com
        </Text>
      </View>
      <Image
        source={{
          uri: REMOTE_IMAGE_PATH,
        }}
        style={{
          width: '100%',
          height: 100,
          resizeMode: 'contain',
          margin: 5
        }}
      />
      <TouchableOpacity
        style={styles.button}
        onPress={checkPermission}>
        <Text style={styles.text}>
          Download Image
        </Text>
      </TouchableOpacity>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  button: {
    width: '80%',
    padding: 10,
    backgroundColor: 'orange',
    margin: 10,
  },
  text: {
    color: '#fff',
    fontSize: 20,
    textAlign: 'center',
    padding: 5,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device:

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

Android

File Download Android 1   File Download Android 2   File Download Android 3   File Download Android 4

iOS

File Download iOS 1   File Download iOS 2

This was how to download an Image in React Native from any URL. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

15 thoughts on “How to Download an Image in React Native from any URL”

  1. This works great. Thank you. Just one query – how can i download the image in a specific directory (creating a new one) and the get the image from that directory.

    Reply
  2. This code works fine,
    I need one help, Please

    LOG file:///data/user/0/com.qr/cache/04efbb0e-1f99-4f96-8ace-af341ccd6b61.png

    hi, if we have image like above img uri and i need to save this image in gallery,
    can you please tell me how this image be saved in pictures directory.

    Thanks!

    Reply
    • I got it, android and iOS is working..
      // let RootDir = fs.dirs.PictureDir;
      const RootDir = Platform.OS == ‘ios’ ? fs.dirs.DocumentDir : fs.dirs.DownloadDir

      thank you.

      Reply
  3. Suppose we are displaying map and graph with the help of backend data on our project and we want to give the functionality to the user to download that map and graph on click save option, so how we can do that… “Can anyone just me any package or anything that is useful for me for this task?”

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.