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

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')

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值