Download file using Blob in react-native
Asked Answered
D

2

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

Devisable answered 2/7, 2018 at 9:56 Comment(1)
Not sure when it was added but Expo now has a FileSystem API that should give you what you need.Ravine
F
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.

Friel answered 29/3, 2021 at 13:26 Comment(0)
R
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

Rotorua answered 11/12, 2021 at 1:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.