2016-07-29 104 views
3

我正在使用react-native-fs,我试图将pdf文件的base64保存到我的android模拟器文件系统。如何将pdf保存到android文件系统,然后查看PDF - react-native

我从服务器收到base64编码的pdf。
我然后解码的base64字符串行:

var pdfBase64 = 'data:application/pdf;base64,'+base64Str; 

saveFile的()函数

saveFile(filename, pdfBase64){ 

    // create a path you want to write to 
    var path = RNFS.DocumentDirectoryPath + '/' + filename; 

    // write the file 
    RNFS.writeFile(path, base64Image, 'base64').then((success) => { 
     console.log('FILE WRITTEN!'); 
    }) 
    .catch((err) => { 
     console.log("SaveFile()", err.message); 
    }); 
} 

错误
当我尝试保存pdfBase64的saveFile的()函数捕获以下错误:

bad base-64 

问题
任何人都可以说出我在做什么错在哪里? 谢谢。

回答

13

对于有同样问题的人,这里是解决方案。

反应-nativive-PDF的视图必须采取文件路径pdf_base64。

首先,我使用react-native-fetch-blob向服务器请求pdf base64(因为RN提取API尚不支持BLOB)。

此外,我发现react-native-fetch-blob也有一个FileSystem API,它比'react-native-fs'库有更好的记录和更容易理解的方法。 (Check out its FileSystem API documentation

接收的base64 PDF并将其保存到指定文件路径:

var RNFetchBlob = require('react-native-fetch-blob').default; 

const DocumentDir = RNFetchBlob.fs.dirs.DocumentDir; 

getPdfFromServer: function(uri_attachment, filename_attachment) { 
    return new Promise((RESOLVE, REJECT) => { 

     // Fetch attachment 
     RNFetchBlob.fetch('GET', config.apiRoot+'/app/'+uri_attachment) 
     .then((res) => { 

      let base64Str = res.data; 
      let pdfLocation = DocumentDir + '/' + filename_attachment; 

      RNFetchBlob.fs.writeFile(pdfLocation, pdf_base64Str, 'base64'); 
      RESOLVE(pdfLocation); 
     }) 
    }).catch((error) => { 
     // error handling 
     console.log("Error", error) 
    }); 
} 

我在做什么错了,而不是保存pdf_base64Str文件位置像我一样在上面的例子中。我是这样保存的:

var pdf_base64= 'data:application/pdf;base64,'+pdf_base64Str; 

这是错误的。

填充PDF浏览,文件路径:

<PDFView 
    ref={(pdf)=>{this.pdfView = pdf;}} 
    src={pdfLocation} 
    style={styles.pdf} 
/>