首页 > 解决方案 > 从 iOS React Native FS 上的 url 下载图像

问题描述

我使用 react-native-fs 从 iOS 中的 url 下载图像。我在模拟器上检查它的下载成功路径:

/Users/admin/Library/Developer/CoreSimulator/Devices/443C8F7F-AB92-4217-A999-A7BDBA52A6B6/data/Containers/Data/Application/99958A5C-E350-4855-B8CE-ED6FA999C619/Documents。

在真实设备上,它是路径(iPhone 8 Plus):

/var/mobile/Containers/Data/Application/63F84623-E684-456F-A55A-01E22708C012/Documents/pexels-photo-1109561.jpeg

我尝试设置:const destPath = RNFS.DocumentDirectoryPath + '/images/' + name;

因为当我从真实设备上的照片中选择图像时,这是路径:

file:///var/mobile/Containers/Data/Application/8DE01885-DEFE-4667-B6FF-CE693A0DADB3/Documents/images/1520FCA5-80AB-4300-A7F6-2D2C974D726A.jpg

但它不起作用。我想在照片上显示此图像,这意味着下载成功后我可以立即在我的照片上看到它,如何做到这一点以及其他文件怎么样:mp3,mp4,文本,下载后,如何找到它并显示用户想要阅读的时候?

这是我的代码:

    downloadImage = () => {
   // download(this.props.image.url, '_Subiz/image_' + this.props.image.name);

   this.download(this.props.image.url, `${RNFS.DocumentDirectoryPath}/react-native.png`)

  };


  download = async (target, destination) => {
    try{
      let options = {
        fromUrl: target,
        toFile: destination,
        begin: (res) => {
          console.log(res)
        },
        progress: (data) => {
          console.log(data)
        },
        background: true,
        progressDivider: 1
      };
      console.log(options);
      const request = await RNFS.downloadFile(options).promise
      console.log(request)
    }catch(e){
      console.log(e)
    }
  };

标签: iosreact-native

解决方案


如果您使用https://github.com/joltup/rn-fetch-blob库。您可以下载简单的方式您的图像。您也可以在照片库中看到它

const { fs } = RNFetchBlob;
let Picture = fs.dirs.PictureDir;

 RNFetchBlob
          .config({
                appendExt : 'png',
                fileCache: true,
                path:  Picture+(new Date()).getTime()+'.png',
           })
          .fetch('GET', 'image_url')
          .then((resp) => {
            // the image path you can use it directly with Image component
            console.log(resp.path());
            return resp.readFile('base64'); // If you get base64 file
          })
          .then((base64Data) => { 
            console.log(base64Data);
          }).catch((errorMessage, statusCode) => {
            // error handling
            console.log('errorMessage2:'+errorMessage)
          });

推荐阅读