最近项目有个需求:保存网络图片到相册,IOS用CameraRoll很容易就实现了,Android稍微要麻烦点,思路是用库react-native-fetch-blob(版本0.10.8,也可以用其它库)下载图片到本地并拿到它的路径,然后用CameraRoll把图片塞到相册里,再把下载下来的图片删除掉。核心代码如下,希望能帮到有同样需求的小伙伴们。
import React, {Component} from 'react';
import RNFetchBlob from "react-native-fetch-blob";
import {CameraRoll, Alert} from 'react-native';
export default class DownloadUtil extends Component {
/**
* 保存网络图片到相册
* @param imageUrl 图片url
*/
static saveImageAlbum(imageUrl) {
if (imageUrl.length > 0) {
RNFetchBlob
.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache: true,
appendExt: 'png'
})
.fetch('GET', imageUrl, {
//some headers ..
})
.then((res) => {
// the temp file path
CameraRoll.saveToCameraRoll(res.path()).then(() => {
Alert.alert('', '保存成功!');
DownloadUtil.deleteCacheImage(res.path());
}).catch((err) => {
Alert.alert('', '保存失败!');
console.warn(err.toString());
DownloadUtil.deleteCacheImage(res.path());
});
})
}
}
/**
* 删除缓存图片
* @param path
*/
static deleteCacheImage(path) {
RNFetchBlob.fs.unlink(path).then(() => {
// console.warn('Deleted successfully')
})
}
}