Encoding a image to base64 and upload to web service in Phonegap

admin

Administrator
Staff member
In my PhoneGap project, I use <em>navigator.device.capture.captureImage(captureSuccess, captureError, {limit : 1});</em> to take a picture. In captureSucces function, I get de MediaFile, and I encode it to base64 with this:

Code:
var file="";
var datafile=mediaFiles[0];

var reader = new FileReader();
reader.onload = function(evt){
  file=evt.target.result;
};
reader.readAsDataURL(datafile);

I send this file to a REST Web Service, where I decode the file and save in a folder:

Code:
if (files != null) {
            FileOutputStream fileOutputStream = null;
            try {
                byte[] byteFichero = Base64.decodeBase64(files);
                System.out.println("ARCHIVO " + byteFichero);
                File fich = new File(pathFichero.toString());
                fich.createNewFile();

                fileOutputStream = new FileOutputStream(fich);
                fileOutputStream.write(byteFichero);

                System.out.println("Fichero almacenado ok");
            } catch (Exception e) {
                System.out.println("Excepcion alamacenando fichero "
                        + e.getMessage() + " " + pathFichero);
                return respuesta;
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (IOException ex) {
                    Logger.getLogger(
                            GestionFicheroObjetoService.class.getName())
                            .log(Level.SEVERE, null, ex);
                }

                pathFichero.delete(0, pathFichero.length());
            }
}

Unfortunately, I get an empty image(1 KB). This is because the file value is not correct, it contains:

Code:
{"name":"1385711756945.jpg",
"fullPath":"file:///storage/sdcard0/DCIM/Camera/1385711756945.jpg",
"type":"image/jpeg",
"lastModifiedDate":1385711757000,
"size":2785413,
"start":0,
"end":0}

and when I encode this, I get a little base64 code:


In other examples, they always use <em>input type file</em> to get the file (<a href="http://thiscouldbebetter.wordpress....ing-a-file-to-a-base64-dataurl-in-javascript/" rel="nofollow">http://thiscouldbebetter.wordpress....ing-a-file-to-a-base64-dataurl-in-javascript/</a>) but I have to get the file from Camera.

What is the problem? Some other solution?

Thank you very much.