16

Since React-native v0.54 and Expo SDK v26, Blob is now supported.

I'm trying to download a file available on a URL to my phone (if possible, in my Downloads directory on Android)

All I can find for now is an existing solution using react-native-fetch-blob which seems not necessary anymore.

If anyone could provide a brief example of how to start implementing this feature on Expo Snack

1
  • 1
    Not sure when it was added but Expo now has a FileSystem API that should give you what you need.
    – Petr Bela
    Commented Jul 29, 2020 at 13:48

2 Answers 2

1

Expo

FileSystem

You can use the FileSystem module to download content and save it under a directory on your device.

Installation

  • Managed workflow

$ expo install expo-file-system

  • Bare workflow

On a bare workflow, please follow the instructions here.

Usage

  1. Importing the module
import * as FileSystem from 'expo-file-system';
  1. Create a download resumable.

Using async/await

await FileSystem.downloadAsync(URI, FILE_URI, OPTIONS);

Using promise

FileSystem.downloadAsync(
  'http://techslides.com/demos/sample-videos/small.mp4',
  FileSystem.documentDirectory + 'small.mp4'
)
  .then(({ uri }) => {
    console.log('Finished downloading to ', uri);
  })
  .catch(error => {
    console.error(error);
  });

NOTE

Keep in mind that in order to save/store the content downloaded, you need to pass a valid directory path/uri. i.e FileSystem.documentDirectory + 'small.mp4'. To guarantee that the path to the directory exists, you can use the FileSystem module itself to create a directory. Like this: await FileSystem.makeDirectoryAsync(path, { intermediates: true });. The options object takes the intermediates property that ensures that if you are trying to create a multilevel directory, it will also create the parent folder (if does not exit) for you.

0

XMLHttpRequest

This worked for me. Using the XMLHttpRequest to fetch the file and get the response as a blob.

function downloadFile(url) {
  return new Promise((resolve, reject) => {
      var xhr = new XMLHttpRequest();
      xhr.onerror = reject;
      xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
              resolve(xhr.response);
          }
      };
      xhr.open('GET', url);
      xhr.responseType = 'blob'; // convert type
      xhr.send();
  })
}

You can now download a file with

downloadFile(YOUR_FILE_URL)
    .then((resolve, reject)=>{console.log((resolve)})

Refrence

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.