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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

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

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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"/>
PermissionPurpose
WRITE_EXTERNAL_STORAGETo 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 checkPermission = async () => {
    
    //Function to check the platform
    //If iOS the start downloading
    //If Android then ask for runtime permission

    if (Platform.OS === 'ios') {
      downloadImage();
    } else {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'Storage Permission Required',
            message: 'This 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 'Storage Permission Not Granted'
          alert('Storage Permission Not Granted');
        }
      } catch (err) {
        //To handle permission related issue
        console.warn(err);
      }
    }
  };

  const downloadImage = () => {
    //Main function to download the image
    let date = new Date(); //To add the time suffix in filename
    //Image URL which we want to download
    let image_URL =
      'https://raw.githubusercontent.com/AboutReact/sampleresource/master/gift.png';
    //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: To get the directory path in which 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:
            'https://raw.githubusercontent.com/AboutReact/sampleresource/master/gift.png',
        }}
        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
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

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. 🙂


Related Posts

1 thought on “How to Download an Image in React Native from any URL”

Leave a Comment

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