React-Native:如何在下载文件时显示进度?

Har*_*ani 3 fetch react-native

要求 - 我想显示一个渐进式指示器,显示加载完成的百分比。我已经将 fetch 用于 api 服务调用。是否有可能以任何方式获得下载完成的百分比?或者任何第三方库?

Joh*_*ncy 5

我已经解决了这个问题,这是我使用的 npm rn-fetch-blob

downloadFile() {
  let dirs = RNFetchBlob.fs.dirs;
  const filePath = `${dirs.DocumentDir}`;
  var filename = this.state.invoiceUrl.substring(this.state.invoiceUrl.lastIndexOf('/')+1);
  RNFetchBlob.config({
      path:`${dirs.DownloadDir}/${filename}`,
      fileCache:false
      // addAndroidDownloads: {
      //     notification : true,
      //     useDownloadManager : true,
      //     description: 'TaxiJo Payment Invoice',
      //     mime:'application/pdf',
      //     mediaScannable:true,
      //     path:`${dirs.DownloadDir}/${filename}`
      // },
  })
  .fetch('GET',this.state.invoiceUrl,{
      'Cache-Control' : 'no-store'
  })
  .progress({ interval: 250 },(received,total)=>{
      console.log('progress',received/total);
      this.setState({
          downloadProgress:(received/total)*100
      })
  })
  .then(res=>{
      // RNFetchBlob.fs.stat(res.path()).then(stats=>{
      //     console.log(stats);
      // }).catch(err=>{
      //     console.log('error while getting mimetypes');
      // })
      this.setState({
          downloadProgress:0
      })
      // RNFetchBlob.fs.exists(res.path()).then(exist=>{
      //     console.log(`file ${exist ? '' : 'not'} exists`)
      // }).catch(
      //     err=>console.log('error while checking existance',err)
      // );
      if(Platform.OS === 'ios'){
          RNFetchBlob.ios.openDocument(res.path());
      }else{
          RNFetchBlob.android.actionViewIntent(res.path(),"application/pdf");
      }
  })
  .catch((errorMessage,statusCode)=>{
      console.log("error with downloading file",errorMessage)
  })
}
Run Code Online (Sandbox Code Playgroud)


Sun*_*ita 2

如果你想显示任何图像的下载进度,你可以使用“react-native-fetch-blob”。请参考以下网址了解更多

https://www.npmjs.com/package/react-native-fetch-blob