[RN] React Native 图片保存到相册(支持 Android 和 ios)
React Native 图片保存到相册(支持 Android 和 ios)
原理:
IOS用 RN自带的 CameraRoll,
Android 使用 不成功,需要 react-native-fs 和 CameraRoll 配合使用
已经封装成类:
ImageUtil.js
'use strict'; import React from 'react'; import {CameraRoll, Platform} from 'react-native'; import ToastUtil from "./ToastUtil"; const RNFS = require('react-native-fs'); let ImageUtil = { saveImg: (img) => { if (Platform.OS === 'ios') { let promise = CameraRoll.saveToCameraRoll(img, 'photo'); promise.then(function (result) { ToastUtil.showToast('保存成功!地址:\n' + result); }).catch(function (error) { ToastUtil.showToast('保存失败!\n' + error); }); } else { const RNFS = require('react-native-fs'); //文件处理 const storeLocation = `${RNFS.DocumentDirectoryPath}`; let pathName = new Date().getTime() + Math.random(1000, 9999) + ".png"; let downloadPath = `${storeLocation}/${pathName}`; const ret = RNFS.downloadFile({fromUrl: img, toFile: downloadPath}); ret.promise.then(res => { if (res && res.statusCode === 200) { var promise = CameraRoll.saveToCameraRoll("file://" + downloadPath); promise.then(function (result) { ToastUtil.showToast('保存成功!地址:\n' + result); }).catch(function (error) { ToastUtil.showToast('保存失败!\n' + error); }) } }) } }, }; module.exports = ImageUtil;
Android添加权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
参考:
https://www.jianshu.com/p/6242ec32f75f
本博客地址: wukong1688
本文原文地址:https://www.cnblogs.com/wukong1688/p/11004440.html
转载请著名出处!谢谢~~