必须能够在componentdidmount上给定BASE64字符串的情况下下载PDF

问题描述 投票:1回答:1

我正在尝试根据Base64字符串提供下载PDF的功能。我可以使用“ react-native-view-pdf”查看PDF。只是无法弄清楚如何实际下载文件。这将需要用于android和ios。

我尝试过各种论坛,但可悲的是,没有任何进展。

注意:this.props.pdf是Base64字符串。

尝试1)

var path = RNFetchBlob.fs.dirs.DocumentDir + "/bill.pdf";
RNFetchBlob.fs.writeFile(path, this.props.pdf, "base64").then(res => {
  console.log("File : ", res);
});

尝试2)

RNFetchBlob.config({
  fileCache : true,
  appendExt : 'pdf'
})
.fetch('GET',`${this.props.PDFLink}`)
.then((res) => {
  // open the document directly
  if(Platform.OS == "ios"){
  RNFetchBlob.ios.previewDocument(res.path())
  }
  else{
    RNFetchBlob
    .config({
        addAndroidDownloads : {
            useDownloadManager : true, // <-- this is the only thing required
            // Optional, override notification setting (default to true)
            notification : false,
            // Optional, but recommended since android DownloadManager will fail when
            // the url does not contains a file extension, by default the mime type will be text/plain
            mime : 'application/pdf',
            description : 'File downloaded by download manager.'
        }
    })
    .fetch('GET',`${this.props.PDFLink}`)
    .then((resp) => {
      // the path of downloaded file
      resp.path()
    })
  }
})
.catch(error => {
  console.error(error);
});

我希望看到屏幕加载后,用户可以下载PDF。我已经将它显示给用户,只是希望他们也能够下载文件。

react-native react-native-android react-native-ios react-native-fetch-blob
1个回答
0
投票

要下载文件,您可以使用rn-fetch-blob中的RNFetchBlob.fs.writeFile api,如下所示。您还可以从其文档https://github.com/joltup/rn-fetch-blob#user-content-file-stream

中引用其他文件流api。
RNFetchBlob
        .config({
            addAndroidDownloads : {
                useDownloadManager : true, // <-- this is the only thing required
                // Optional, override notification setting (default to true)
                notification : false,
                // Optional, but recommended since android DownloadManager will fail when
                // the url does not contains a file extension, by default the mime type will be text/plain
                mime : 'application/pdf',
                description : 'File downloaded by download manager.'
            }
        })
        .fetch('GET',`${this.props.PDFLink}`)
        .then((resp) => {
          // the path of downloaded file
          // resp.path()
          let base64Str = resp.data;
          let pdfLocation = RNFetchBlob.fs.dirs.DocumentDir + '/' + 'test.pdf';
          RNFetchBlob.fs.writeFile(pdfLocation, RNFetchBlob.base64.encode(base64Str), 'base64');

        })

希望这会有所帮助:)

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