Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am getting byte array like var byteArr=[12,-123,43,99, ...] from API, Then I am converting it into UTF-8 String by

     var utf8_str = String.fromCharCode.apply([], new Uint8Array(byteArr));

Then converting UTF-8 string to Base64 string by

      var base64_str= window.btoa(utf8_str);

Now I am writing UTF-8 or Base64 string to file (xyz.pdf/xyz.jpg) by FileWriter in Phonegap, but it show me blank file when open it.

function gotWriteFile(dirEntry) {

   dirEntry.getFile(FILE_NAME, {create: true, exclusive: false}, gotFileWriteEntry,  failWrite);
}

function gotFileWriteEntry(fileEntry) {

fileEntry.createWriter(gotFileWriter, failWrite);
}

function gotFileWriter(writer) {

 writer.onwriteend = function(evt) {
        console.log("File write successfully....");
        hideModal();
    };
    writer.write(utf8_str);
    //writer.write(base64_str);
 }

What is solution guys.... ?

like image 213
Saurabh Avatar asked Oct 29 '13 11:10

Saurabh


2 Answers

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.. :)

like image 79
Saurabh Avatar answered Nov 17 '22 12:11

Saurabh


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);
}
like image 1
Vicky Gonsalves Avatar answered Nov 17 '22 13:11

Vicky Gonsalves