ios - 如何从 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) => {
}) ;
解决方案
正如文档中所说,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
推荐阅读
- java - 使用 gradle 和 intellij 为 JavaFX 构建 FatJar,得到 NoClassDefFOundError
- qt-creator - QtCreator - 如何禁用实时代码调试?
- node.js - 云功能 - 更新实时数据库上的数据
- jquery - 如何在动态添加的 HTML 表格行中插入越来越多的数字?
- amazon-web-services - AWS Lambda 和 Cognito 部署错误:一次只能处理一个更新此 UserPool 的请求
- python - 如何将列标题批量添加到目录中的所有 CSV 文件并保留这些文件?
- python - 当我的代码中出现无成员错误时,我的代码如何才能完美运行?
- java - 如何使用列值过滤器查询并获取原始值的最后一个值?
- java - 如何从 npm ls 树输出中提取根级元素?
- python-2.7 - 如何在使用 fit_generator 拟合 keras 模型时修复“MemoryError”?