【问题标题】:Downloading image file with react native fetch blob使用 react native fetch blob 下载图像文件
【发布时间】:2019-02-12 05:21:53
【问题描述】:

我正在尝试学习本机反应以及如何将文件下载到设备。我知道您可以使用本机文件系统来执行此操作,但这不支持我需要的身份验证。 React 本机 fetch blob 确实支持这一点。

出于教育目的,我希望在 react native fetch blob 而不是 react native 文件系统中重新创建此问题的第一个答案中的代码。

我有人可以写一个例子,我会超级坦克。

问题:Downloading data files with React Native for offline use

【问题讨论】:

    标签: react-native


    【解决方案1】:
    downloadImage(){
       var date      = new Date();
       var url       = "http://debasish.com/image.jpg";
       var ext       = this.getExtention(url);
       ext = "."+ext[0];
       const { config, fs } = RNFetchBlob ; 
       let PictureDir = fs.dirs.PictureDir
       let options = {
       fileCache: true,
        addAndroidDownloads : {
          useDownloadManager : true,
          notification : true,
          path:  PictureDir + "/image_"+Math.floor(date.getTime() 
              + date.getSeconds() / 2)+ext,
         description : 'Image'
          }
       }
        config(options).fetch('GET', url).then((res) => {
          Alert.alert("Download Success !");
       });
    }
      getExtention(filename){
        return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : 
    undefined;
    

    }

    【讨论】:

    • 使用 rn-fetch-blob 下载图像文件。它适用于 Android(React Native)。在 expo 中它不会工作,因为 Expo 目前不支持 rn-fetch-blob。
    • 请编辑您的答案以在其中包含信息/解释(不在 cmets 中),并确保您的代码正确缩进。最后的大括号不是代码格式的(代码需要 4 个空格)。
    【解决方案2】:

    试试这个,它在 Android 上可以正常工作:

    export const download = (url, name) => {
      const { config, fs } = RNFetchBlob;
      let PictureDir = fs.dirs.PictureDir;
      let options = {
        fileCache: true,
        addAndroidDownloads: {
          useDownloadManager: true,
          notification: true,
          path: PictureDir + name,
          description: t('downloading_file')
        }
      };
      config(options)
        .fetch('GET', url)
        .then(res => {
          if (res.data) {
            alert(t('download_success'));
          } else {
            alert(t('download_failed'));
          }
        });
    };
    

    【讨论】:

    猜你喜欢
    • 2017-11-22
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 2018-11-24
    • 2020-05-04
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多