172 字
1 分钟
rn中对于安卓与ios下载远程图片的处理
安装环境
使用包
import RNFS from 'react-native-fs';import CameraRoll from '@react-native-community/cameraroll';安装
npm install react-native-fs --savenpm install @react-native-community/cameraroll --save其中 CameraRoll 用来将图片存储到手机相册,使用了 save() 方法
save(tag, {type, album})IOS
CameraRoll.save('网络图片url', 'photo') .then(() => { Alert.alert('保存成功!'); }) .catch(function (error) { Alert.alert('保存失败!');});Android
由于安卓上处理图片时,tag只能为本地图片,若为远程图片会被截掉域名导致获取不到图片,对比如下
ios:https://blog.uimentama.com/blogfile/uiavatar.jpgAndroid:/blogfile/uiavatar.jpg因此需要使用react-native-fs来将远程图片临时下载至本地缓存,再通过cameraroll下载缓存中的文件至本地,代码如下:
// 获取后缀名const suffix = imgUrl.substring('网络图片url'.lastIndexOf('.'));// 获取存储路径(存放路径+自定义文件名+后缀名)// ExternalCachesDirectoryPath(String)外部缓存目录的绝对路径(仅适用于Android)const downloadDest = `${RNFS.ExternalCachesDirectoryPath}/marrydream_${ new Date().getTime() + suffix}`;RNFS.downloadFile({ fromUrl: imgUrl, toFile: downloadDest,}) .promise.then((res) => { // 调用cameraRoll,与ios不同的是tag变为缓存图片的url CameraRoll.save(downloadDest, 'photo') .then(() => { Alert.alert('保存成功!'); }) .catch(function (error) { Alert.alert('保存失败!'); });}).catch((err) => { Alert.alert('保存失败!');});同时兼容ios与Android
只需通过判断系统,分别对cameraRoll使用不同的tag即可,若为安卓则添加 fs 处理操作,ios 则直接使用
整体代码如下:
import RNFS from 'react-native-fs';import CameraRoll from '@react-native-community/cameraroll';import {Alert, Platform} from 'react-native';import {getLibraryPermission} from '@/utils/permissions';
const CameraRollSave = (imgUrl, callback = () => {}) => { CameraRoll.save(imgUrl, 'photo') .then(() => { callback(); Alert.alert('保存成功!'); }) .catch(function (error) { Alert.alert('保存失败!'); });};
export default function saveImage(imgUrl, callback = () => {}) { const suffix = imgUrl.substring(imgUrl.lastIndexOf('.')); // 这里使用自己封装的方法事先判断了一下有无存储权限 getLibraryPermission().then(() => { if (Platform.OS === 'ios') { return CameraRollSave(imgUrl); } const downloadDest = `${RNFS.ExternalCachesDirectoryPath}/marrydream_${ new Date().getTime() + suffix }`; RNFS.downloadFile({ fromUrl: imgUrl, toFile: downloadDest, }) .promise.then((res) => { CameraRollSave(downloadDest, callback); }) .catch((err) => { Alert.alert('保存失败!'); }); });} 分享
如果这篇文章对你有帮助,欢迎分享给更多人!
rn中对于安卓与ios下载远程图片的处理
https://marrydream.top/posts/web前端/rn中对于安卓与ios下载远程图片的处理/ 部分信息可能已经过时
相关文章 智能推荐