React Native 从 url 下载图像并保存在图库中

问题描述 投票:0回答:3

我想从 URL 下载图像并保存在图库中。

此源在 Android 上运行良好,但不适用于 iOS。

import RNFetchBlob from "rn-fetch-blob";


let imgUrl = 'https://static.scientificamerican.com/sciam/cache/file/EAF12335-B807-4021-9AC95BBA8BEE7C8D_source.jpg'

let newImgUri = imgUrl.lastIndexOf('/');
let imageName = imgUrl.substring(newImgUri);

let dirs = RNFetchBlob.fs.dirs;
let path = Platform.OS === 'ios' ? dirs['MainBundleDir'] + imageName : dirs.PictureDir + imageName;

 RNFetchBlob.config({
     fileCache: true,
     appendExt: 'png',
     indicator: true,
     IOSBackgroundTask: true,
     path: path,
     addAndroidDownloads: {
         useDownloadManager: true,
         notification: true,
         path: path,
         description: 'Image'
      },

     }).fetch("GET", imgUrl).then(res => { 
            console.log(res, 'end downloaded') 
   });

是否需要 iOS 的一项权限才能将照片保存在图库中?

react-native photo-gallery imagedownload
3个回答
9
投票

对于 iOS,您无需使用 fetch-blob 并下载它。 你需要使用react-native中的CameraRoll并调用saveToCameraRoll()

https://facebook.github.io/react-native/docs/cameraroll

import RNFetchBlob from "rn-fetch-blob";
import { CameraRoll, Platform } from "react-native";

let imgUrl = 'https://static.scientificamerican.com/sciam/cache/file/EAF12335-B807-4021-9AC95BBA8BEE7C8D_source.jpg'

let newImgUri = imgUrl.lastIndexOf('/');
let imageName = imgUrl.substring(newImgUri);

let dirs = RNFetchBlob.fs.dirs;
let path = Platform.OS === 'ios' ? dirs['MainBundleDir'] + imageName : dirs.PictureDir + imageName;

saveToGallery = () => {
  if (Platform.OS == 'android') {

    RNFetchBlob.config({
      fileCache: true,
      appendExt: 'png',
      indicator: true,
      IOSBackgroundTask: true,
      path: path,
      addAndroidDownloads: {
        useDownloadManager: true,
        notification: true,
        path: path,
        description: 'Image'
      },

    }).fetch("GET", imgUrl).then(res => {
      console.log(res, 'end downloaded')
    });
  } else {
    CameraRoll.saveToCameraRoll(imgUrl);
  }
}

4
投票

您必须使用相机胶卷。

  • npm install @react-native-community/cameraroll --save

  • react-native 链接@react-native-community/cameraroll

  • 来自:

    从“react-native”导入{CameraRoll};

    从“@react-native-community/cameraroll”导入CameraRoll;


0
投票

截至 2023 年,

@react-native-community/cameraroll
已弃用,CameraRoll 已从 React Native 库中删除,

按照以下网址的说明进行操作: https://github.com/react-native-cameraroll/react-native-cameraroll

© www.soinside.com 2019 - 2024. All rights reserved.