Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a file with react-native?

Tags:

react-native

I'm trying to download and save a file with rn-fetch-blob. (I haven't been able to do it without a library since apparently react-native only implements a subset of the browser's fetch interface). My code is something like:

import RNFetchBlob from 'rn-fetch-blob'

RNFetchBlob
  .config({ path: RNFetchBlob.fs.dirs.DocumentDir + '/medias/foo' })
  .fetch('GET', 'http://example.com/files/foo', { 'Cache-Control': 'no-store' })
  .then(res => {
    console.log('file saved to ' + res.path())
  })

and I'm getting:

[RNFetchBlobRequest] session didCompleteWithError (null)
[RNFetchBlobRequest] session didBecomeInvalidWithError (null)

Possible Unhandled Promise Rejection (id: 0):
Error: No such file '/Users/me/Library/Developer/CoreSimulator/Devices/0781956D-D2E6-4BC8-8943-62DA9B111BEF/data/Containers/Data/Application/A39E6A35-D248-4019-9CA0-1F9063E40161/Documents/medias/foo'
Error: No such file '/Users/me/Library/Developer/CoreSimulator/Devices/0781956D-D2E6-4BC8-8943-62DA9B111BEF/data/Containers/Data/Application/A39E6A35-D248-4019-9CA0-1F9063E40161/Documents/medias/foo'
    at createErrorFromErrorData (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:1824:15)
    at http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:1777:25
    at MessageQueue.__invokeCallback (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:2135:16)
    at http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:1952:16
    at MessageQueue.__guard (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:2070:9)
    at MessageQueue.invokeCallbackAndReturnFlushedQueue (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:1951:12)
    at http://localhost:8081/debugger-ui/debuggerWorker.js:72:58

The file is not created, the 'medias' directory in the (virtual) device remains empty.

How to download and save a file with react-native?

like image 957
vmarquet Avatar asked Oct 12 '25 13:10

vmarquet


2 Answers

let try this.

import RNFetchBlob from 'rn-fetch-blob'
import Share from 'react-native-share'
import RNFS from 'react-native-fs'
import {Alert, Platform} from 'react-native'

const download = (url) => {
  let dirs = RNFetchBlob.fs.dirs
  try {
    if (Platform.OS === 'android') {
      const configOptions = { fileCache: true }
      RNFetchBlob.config(configOptions)
      .fetch('GET', url, {
      'Authorization': '', //yourTokenIfHave
      'Content-Type': '' // 'application/octet-stream'
    })
    .then(resp => {
      return resp.readFile('base64')
    })
    .then(async base64Data => {
      base64Data = `data:application/pdf;base64,` + base64Data
      await Share.open({ url: base64Data })
      // remove the image or pdf from device's storage
      await RNFS.unlink(filePath)
    })
} else {
  RNFetchBlob
    .config({
      fileCache: true,
      path: dirs.DocumentDir + `/${itemPDF.fileName}`
    })
    .fetch('GET', url, {
      'Authorization': '',
      'Content-Type': '' // 'application/octet-stream'
    })
    .then(async (res) => {

      // the temp file path
      if (res && res.path()) {
        const filePath = res.path()
        let options = {
          type: 'application/pdf',
          url: filePath
        }
        await Share.open(options)
        await RNFS.unlink(filePath)
      }
    })
    .catch((error) => {
      console.log(error)
    })
    }
  } catch (error) {
   console.log('download: ', error)
 }
}
like image 101
Tim Avatar answered Oct 16 '25 06:10

Tim


I did not try again rn-fetch-blob, I ended up using react-native-fs and it works. react-native-fs seems more popular and more maintained.

(I did a react-native version upgrade before trying again to save a file, so maybe it wasn't entirely due to a bug in rn-fetch-blob but also due to using an old react-native version.)

like image 34
vmarquet Avatar answered Oct 16 '25 07:10

vmarquet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!