1.依赖
https://github.com/react-native-cameraroll/react-native-cameraroll#save
https://github.com/itinance/react-native-fs
2. util.js
import { PermissionsAndroid, Platform } from 'react-native';
import RNFS from 'react-native-fs';
import CameraRoll from '@react-native-community/cameraroll';
// 校验安卓授权情况
async function hasAndroidPermission() {
const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
const hasPermission = await PermissionsAndroid.check(permission);
if (hasPermission) {
return true;
}
const status = await PermissionsAndroid.request(permission);
return status === 'granted';
}
/**
* 下载网络图片
* @param uri 图片地址
* @returns {*}
*/
export const downloadImage = (uri: string) => {
if (!uri) return null;
return new Promise((resolve, reject) => {
let timestamp = new Date().getTime(); //获取当前时间错
let random = String((Math.random() * 1000000) | 0); //六位随机数
let dirs =
Platform.OS === 'ios'
? RNFS.LibraryDirectoryPath
: RNFS.ExternalDirectoryPath; //外部文件,共享目录的绝对路径(仅限android)
const downloadDest = `${dirs}/${timestamp + random}.png`;
const formUrl = uri;
const options = {
fromUrl: formUrl,
toFile: downloadDest,
background: true,
begin: (res) => {
// console.log('begin', res);
// console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
},
};
try {
const ret = RNFS.downloadFile(options);
ret.promise
.then((res) => {
// console.log('success', res);
// console.log('file://' + downloadDest)
var promise = CameraRoll.save(downloadDest);
promise
.then(function (result) {
// alert('保存成功!地址如下:\n' + result);
})
.catch(function (error) {
console.log('error', error);
// alert('保存失败!\n' + error);
});
resolve(res);
})
.catch((err) => {
reject(new Error(err));
});
} catch (e) {
reject(new Error(e));
}
});
};
/**
* 保存网络图片
* @param url 图片地址
* @returns {*}
*/
export default async function savePicture(url: string) {
if (Platform.OS === 'android' && !(await hasAndroidPermission())) {
return;
}
return downloadImage(url);
}
3.使用
import savePicture from 'util'
savePicture('https://www.xxx.com/logo.png')