首页 > 解决方案 > 如何从 iOS 的 react-native 中的 url 下载文件

问题描述

我无法在 react-native 中从 url 下载图像,我使用的是“react-native-fetch-blob”,它适用于 android 但不适用于 iOS。让 PictureDir = fs.dirs.PictureDir; 这是 iOS 未定义的 PicureDir。

这是代码:

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) => {
}) ;

标签: iosfilereact-nativeurldownload

解决方案


正如文档中所说,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)

您应该在 iOS 上使用DocumentDir或保存文件CacheDir

你可以做这样的事情,这将允许你根据操作系统使用不同的目录

import { Platform } from 'react-native';

...

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

更新

我尝试了您更新的代码并且它可以工作,但是我确实必须对其进行调整。

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

使用 DownloadManager 时,config 中的 fileCache 和 path 属性不会生效,因为 Android DownloadManager 只能将文件存储到外部存储,还要注意 Download Manager 只能支持 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


推荐阅读