将图片从url保存到App的某个文件夹(例如tmp,文档)中以供离线使用

时间:2018-12-18 06:32:22

标签: image react-native offline-mode

一旦加载URL,我想保存图像,然后将其保存在文档或tmp文件夹等位置,并以脱机模式使用以保存图像。

我尝试使用react-native-fs,但是没有成功,它给出了错误。

2 个答案:

答案 0 :(得分:0)

您可以通过将图像转换为base64来保存URL中的图像。之后,您可以对图像执行任何操作,例如将字节重建/写入实际图像。

答案 1 :(得分: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)
  }
}