How to Download an Image from url in React Native (Android)

Last Updated on December 11, 2020.

Downloading an image to your Android device can be achieved using the React Native Fetch blob library. Before downloading an image in Android, your app must require permission to write external memory.

Hence, first you should add permission in Android manifest file.

Go to yourProject/android/app/src/main/AndroidManifest.xml and add the following line.

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

Now, the following code shows you how to download an image when a button is pressed. It uses PermissionsAndroid API to ask permission through your app. Be make sure to configure rn-fetch-blob library by using the instructions given here.

Class Component

import React, {Component} from 'react';
import {
  View,
  Text,
  Button,
  Alert,
  ToastAndroid,
  PermissionsAndroid,
  ActivityIndicator,
} from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
    };
  }

  actualDownload = () => {
    this.setState({
      loading: true,
    });
    let dirs = RNFetchBlob.fs.dirs;
    RNFetchBlob.config({
      // add this option that makes response data to be stored as a file,
      // this is much more performant.
      path: dirs.DownloadDir + '/path-to-file.png',
      fileCache: true,
    })
      .fetch(
        'GET',
        'https://cdn.pixabay.com/photo/2014/12/21/23/34/cherry-575547_960_720.png',
        {},
      )
      .then((res) => {
        this.setState({
          loading: false,
        });
        ToastAndroid.showWithGravity(
          'Your file has been downloaded to downloads folder!',
          ToastAndroid.SHORT,
          ToastAndroid.BOTTOM,
        );
      });
  };

  async downloadFile() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: 'Storage Permission',
          message: 'App needs access to memory to download the file ',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        this.actualDownload();
      } else {
        Alert.alert(
          'Permission Denied!',
          'You need to give storage permission to download the file',
        );
      }
    } catch (err) {
      console.log(err);
    }
  }
  render() {
    return (
      <View>
        <Text> Download Files in Android </Text>
        <Button onPress={() => this.downloadFile()} title="Download" />
        {this.state.loading ? (
          <ActivityIndicator size="small" color="#0000ff" />
        ) : null}
      </View>
    );
  }
}

Function component

import React, {useState} from 'react';
import {
  View,
  Text,
  PermissionsAndroid,
  Button,
  ActivityIndicator,
  ToastAndroid,
  Alert,
} from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';

const App = () => {
  const [loading, setLoading] = useState(false);

  const actualDownload = () => {
    setLoading(true);
    let dirs = RNFetchBlob.fs.dirs;
    RNFetchBlob.config({
      // add this option that makes response data to be stored as a file,
      // this is much more performant.
      path: dirs.DownloadDir + '/path-to-file.png',
      fileCache: true,
    })
      .fetch(
        'GET',
        'https://cdn.pixabay.com/photo/2014/12/21/23/34/cherry-575547_960_720.png',
        {},
      )
      .then((res) => {
        setLoading(false);
        ToastAndroid.showWithGravity(
          'Your file has been downloaded to downloads folder!',
          ToastAndroid.SHORT,
          ToastAndroid.BOTTOM,
        );
      });
  };
  const downloadFile = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: 'Storage Permission',
          message: 'App needs access to memory to download the file ',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        actualDownload();
      } else {
        Alert.alert(
          'Permission Denied!',
          'You need to give storage permission to download the file',
        );
      }
    } catch (err) {
      console.log(err);
    }
  };
  return (
    <View>
      <Text> Download Files in Android </Text>
      <Button onPress={() => downloadFile()} title="Download" />
      {loading ? <ActivityIndicator size="small" color="#0000ff" /> : null}
    </View>
  );
};

export default App;

I hope this react native tutorial to download image is helpful for you.

5 thoughts on “How to Download an Image from url in React Native (Android)”

    1. Very nice. Works like a charm. As of 2020, ProgressBarAndroid is deprecated in react-native. So install the community version, @react-native-community/progress-bar-android. The component is now called just ProgressBar. Some small differences in props, but otherwise the entire code in this article is usable as it is. These differences can be checked at the component’s github pagehttps://github.com/react-native-community/progress-bar-android

Leave a Reply

%d bloggers like this: