如何在iOS的React-Native中从URL下载文件

时间:2019-01-08 21:00:38

标签: ios file react-native url download

我无法在react-native中从url下载图像,我使用的是'react-native-fetch-blob',它在android上工作正常,但在iOS上工作正常。 让PictureDir = fs.dirs.PictureDir; 这是PicureDir对于iOS未定义。

这是代码:

const { config, fs } = RNFetchBlob;

let PictureDir = Platform.OS === 'ios' ? fs.dirs.DocumentDir : fs.dirs.PictureDir;
let options = {
  fileCache: true,
  addAndroidDownloads : {
    useDownloadManager : true, // setting it to true will use the device's native download manager and will be shown in the notification bar.
    notification : false,
    path:  PictureDir + "/me_"+Math.floor(date.getTime() + date.getSeconds() / 2), // this is the path where your downloaded file will live in
    description : 'Downloading image.'
  }
}

config(options).fetch('GET', "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?cs=srgb&dl=beauty-bloom-blue-67636.jpg&fm=jpg").then((res) => {
}) ;

1 个答案:

答案 0 :(得分:0)

正如文档中所述,PictureDir仅在Android中可用。

https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-API#dirs

DocumentDir
CacheDir
MainBundleDir (Can be used to access files embedded on iOS apps only)
DCIMDir (Android Only)
DownloadDir (Android Only)
MusicDir (Android Only)
PictureDir (Android Only)
MovieDir (Android Only)
RingtoneDir (Android Only)
SDCardDir (0.9.5+ Android Only)

您应使用DocumentDirCacheDir在iOS上保存文件

您可以执行类似的操作,这将允许您根据操作系统使用不同的目录

import { Platform } from 'react-native';

...

let PictureDir = Platform.OS === 'ios' ? fs.dirs.DocumentDir : fs.dirs.PictureDir;

更新

我尝试了更新的代码,它可以工作,但是我确实需要对其进行一些调整。

使用addAndroidDownloads时必须注意,您无法为Android设置自己的路径。

  

使用DownloadManager时,config中的fileCache和路径属性   不会生效,因为Android DownloadManager只能存储   文件添加到外部存储,还请注意,下载管理器只能   支持GET方法,这意味着请求主体将被忽略。

https://github.com/joltup/rn-fetch-blob#android-media-scanner-and-download-manager-support

因此要设置路径,以便iOS知道将文件存储在何处,您应该在addAndroidDownloads对象之外设置路径,以使您的选择变为:

let options = {
  fileCache: true,
  addAndroidDownloads : {
    useDownloadManager : true, // setting it to true will use the device's native download manager and will be shown in the notification bar.
    notification : false,
    description : 'Downloading image.'
  },
  path:  PictureDir + "/me_"+Math.floor(date.getTime() + date.getSeconds() / 2) // this is the path where your downloaded file will live in
}

对于iOS,它将忽略addAndroidDownloads中的设置,并且文件将保存在设备的文档目录中,因为这是给出的路径。

如果要将文件保存到iOS上的设备的图片库中,则必须使用CameraRoll

您可以在https://stackoverflow.com/a/54125033/5508175

上看到我给出的使用答案。