React Native Android 保存网络图片到相册

最近项目有个需求:保存网络图片到相册,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')
        })
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值