Reputation: 715
I used writeFile(path, file, data, replace) method in $cordovaFile to write new file(pdf, jpg, text ). as a data I got data stream from restful service ..(it looks like %PDF-1.5↵%����↵1 0 obj↵..) The problem is I can write a file but it opens as a blank pdf but file size is correct. for data field I used data stream itself, blob object(var blob = new Blob([data], { type: 'application/pdf' });) ,
This is my code
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");
});
Please help me out.... any ideas...?
Upvotes: 2
Views: 859
Reputation: 715
Using this method text files can write correctly. problem was .pdf .png file writing. so I use this method to write file. that works for me.
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;
}
Upvotes: 1