2016-07-29 100 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} 
/>