2016-08-01 96 views
2

我用$ cordovaFile中的writeFile(path,file,data,replace)方法寫入新文件(pdf,jpg,text)。 作爲一個數據我從寧靜的服務獲得數據流..(它看起來像%PDF-1.5↵% ↵10obj↵..) 問題是我可以寫一個文件,但它作爲一個空白打開pdf,但文件大小是正確的。 用於數據字段我使用的數據流本身,blob對象(VAR團塊=新斑點([數據],{類型: '應用/ PDF'});),

這是我的代碼

var path = cordova.file.externalRootDirectory; 
$cordovaFile.writeFile(path, "myCreatedPdf.pdf", blob, true) 
.then(function(success){ 
    console.log("file"); 
    $cordovaFileOpener2.open(
     success.target.localURL,'application/pdf' 
    ); 
}, function (error) { 
    console.log("error"); 
});   

請幫我....任何想法...?

+0

您是否曾嘗試先創建文本文件? –

回答

1

使用此方法文本文件可以正確寫入。問題是.pdf .png文件寫入。所以我用這個方法來寫文件。這對我行得通。

function saveFile(pdfBlob, fileName) { 
    var deferred = $q.defer(); 

    var filePath = ""; 
    try { 
     console.log('SaveFile: requestFileSystem'); 
     window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail); 
    } catch (e) { 
     console.error('SaveFile_Err: ' + e.message); 
     deferred.reject(e); 
     throw ({ code: -1401, message: 'unable to save report file' }); 
    } 


    function gotFS(fileSystem) { 
     fileSystem.root.getDirectory("TokenReader", { create: true }, gotDir); 
    } 

    function gotDir(dirEntry) { 
     //console.error('SaveFile: gotFS --> getFile'); 
     //dirEntry.getFile("rptSampleNew.pdf", {create: true, exclusive: false}, gotFileEntry, fail); 
     dirEntry.getFile(fileName, { create: true, exclusive: false }, gotFileEntry, fail); 
    } 

    function gotFileEntry(fileEntry) { 
     //console.error('SaveFile: gotFileEntry --> (filePath) --> createWriter'); 
     filePath = fileEntry.toURL(); 
     fileEntry.createWriter(gotFileWriter, fail); 
    } 

    function gotFileWriter(writer) { 
     //console.error('SaveFile: gotFileWriter --> write --> onWriteEnd(resolve)'); 
     writer.onwriteend = function (evt) { 
      $timeout(function() { 
       deferred.resolve(filePath); 
      }, 100); 
     }; 

     writer.onerror = function (e) { 
      console.log('writer error: ' + e.toString()); 
      deferred.reject(e); 
     }; 

     writer.write(pdfBlob); 
    } 

    function fail(error) { 
     console.log(error.code); 
     deferred.reject(error); 
    } 

    return deferred.promise; 
}