Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

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

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

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:

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:

{"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:

[B@877d81

In other examples, they always use input type file to get the file (http://thiscouldbebetter.wordpress.com/2013/07/03/converting-a-file-to-a-base64-dataurl-in-javascript/) but I have to get the file from Camera.

What is the problem? Some other solution?

Thank you very much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i am also facing this issue. i got solution after long time search

camera success function:

function capturesuceess(mediafiles){

var uploadimageurl= mediafile
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, rfail);


 window.resolveLocalFileSystemURI(uploadimageurl, onResolveSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
    console.log(fileSystem.name);
}
function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
function onResolveSuccess(fileEntry) {


    filenameofajax=fileEntry.name;

    var efail = function(evt) {
        console.log("File entry error  "+error.code);
    };
    var win=function(file) {
        console.log(file);
        alert(bytesToSize(file.size));
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            console.log("read success");
              console.log(evt.target.result);
            var basestr=evt.target.result;

            basestr= basestr.substr(basestr.indexOf("base64,")+7,basestr.length);
         console.log(basestr);// this is a base64 string


        };
        reader.readAsDataURL(file);
    };
    fileEntry.file(win, efail);
}

try this working fine. and also u write efail and fail function with empty enjoy with phonegap


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...