How to write UTF-8 or Base64 data into a file (jpg/doc/pdf) on local storage(sdcard) in Phonegap

寵の児 提交于 2019-12-03 07:30:39

I have found solution to create file by byte array in Phonegap.

In phonegap, Text and Binary data are supported for Android and iOS to write into file. So I have convert BYTE array to BINARY array, then write by FileWriter.

 var byteArr=[12,-123,43,99, ...] ;
 var UTF8_STR = new Uint8Array(byteArr);  // Convert to UTF-8...                
 var BINARY_ARR=UTF8_STR.buffer;         // Convert to buffer...    

Then pass 'BINARY_ARR' to FileWriter to write in file.

 function gotFileWriter(writer) {
     writer.onwriteend = function(evt) {
     console.log("File write successfully....");        
   };
   writer.write(BINARY_ARR);   
 }

Have a nice day.. :)

try this (make sure u are getting utf8_str properly):

var utf8_str = String.fromCharCode.apply([], new Uint8Array(byteArr));
var base64_str= window.btoa(utf8_str);
function writeFile() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
    fileSystem.root.getFile(FILE_NAME, {create: true}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
    writer.onwrite = function (evt) {
        alert('done');
    }
    writer.write(utf8_str);
}
function fail(error) {
    console.log(error.code);
}

I had issues on another project with btoa not doing a proper conversion, so I ended up using Base64 binary in my project to decode the Base64 response.

What I noticed was that the file I transferred was bigger when saved on the phone compared to the file residing on the server.

Maybe that is the case for you as well?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!