如何使用react-native保存文件?

时间:2018-12-18 14:18:38

标签: react-native

我正在尝试使用rn-fetch-blob下载并保存文件。 (我没有库就无法做到这一点,因为显然react-native仅实现了浏览器fetch接口的一个子集)。我的代码是这样的:

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())
  })

我得到:

[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

该文件未创建,(虚拟)设备中的“媒体”目录仍然为空。

如何使用react-native下载和保存文件?

4 个答案:

答案 0 :(得分:0)

您的问题似乎在于对该目录.config({ path: RNFetchBlob.fs.dirs.DocumentDir + '/medias/foo' })的访问权限,可能是因为/medias/foo不存在,请尝试在没有特定路径的情况下进行操作。

我总是以这种方式使用它,如docs中所述:

RNFetchBlob
  .config({
    // add this option that makes response data to be stored as a file,
    // this is much more performant.
    fileCache : true,
  })
  .fetch('GET', 'http://www.example.com/file/example.zip', {
    //some headers ..
  })
  .then((res) => {
    // the temp file path
    console.log('The file saved to ', res.path())
  })

答案 1 :(得分:0)

我遇到了同样的问题,如果您使用的是“ rn-fetch-blob”:将0.10.14切换到“ 0.10.13”,请选中https://github.com/joltup/rn-fetch-blob/issues/266https://github.com/wonday/react-native-pdf/issues/286

答案 2 :(得分:0)

让我们尝试一下。

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)
 }
}

答案 3 :(得分:0)

我没有再尝试rn-fetch-blob,最终我使用了react-native-fs并成功了。 react-native-fs似乎更受欢迎,而且维护程度更高。

(在再次尝试保存文件之前,我做了react-native版本升级,因此,这可能不完全是由于rn-fetch-blob中的错误,还因为使用了旧的react-native版本。)