React Native - save photos and videos to the device gallery

Saving photos and videos to an android / ios device is a challenge for many React Native developers. In this article I will show how you can easily and painlessly save photos via url to the device.

First, we need two libraries:

  1. @ react-native-community / cameraroll - provides access to the gallery (I succeeded only with version 1.4.0. There were well-known errors on versions “fresher”, write if you succeeded with a different version)
  2. rn-fetch-blob - access to local application files. It should be noted that this library works with react native version 0.60 and higher


IOS


On ios, everything turned out to be very simple:

1. Add to Info.plist
<key>NSCameraUsageDescription</key>
<string></string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string></string>
<key>NSPhotoLibraryUsageDescription</key>
<string></string>

2. Implementation
import CameraRoll from '@react-native-community/cameraroll';

const saveImageInDevice = async (url) => {
    await CameraRoll.saveToCameraRoll(url, 'photo');
}

That's all! The saveImageInDevice function accepts the link address as input. CameraRoll.saveToCameraRoll downloads the file and saves it to the device gallery. The second parameter of the saveToCameraRoll method can also be “video”

Android


Android devices are a bit more complicated. The fact is that on android, the saveToCameraRoll method does not know how to work with an external url. First we need to upload the file to external storage, and then to the gallery:

import {PermissionsAndroid} from 'react-native';
import CameraRoll from '@react-native-community/cameraroll';
import RNFetchBlob from 'rn-fetch-blob';

//      
const checkAndroidPermission = async () => {
    const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
    await PermissionsAndroid.request(permission);
};

const saveImageInDevice = async (url) => {
     await checkAndroidPermission();
        let res = await RNFetchBlob
          .config({
            fileCache : true,
            appendExt : 'jpg' 
          })
          .fetch('GET', url);
     url = res.path();
     await CameraRoll.saveToCameraRoll(url, 'photo');
}


RNFetchBlob.fetch by GET request will upload the file to external storage and pass the url of this file. Then CameraRoll.saveToCameraRoll will upload this file to the gallery.

That's all. Thank you for the attention!

Links:
github.com/react-native-community/react-native-cameraroll
github.com/joltup/rn-fetch-blob

All Articles