0
votes

I am making an app (ionic) that upload images as a string to some online service, I only have the URI of the image on the device, how can I load the image and convert it to base64 string, and later view it in the app?

1

1 Answers

0
votes

Use FileReader:

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

By create function:

function convertFileToDataURLviaFileReader(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var reader  = new FileReader();
        reader.onloadend = function () {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}

Then call it to get base64 data:

convertFileToDataURLviaFileReader('yourUrlHere',function(base64Data){
    //do something with base64Date

    //show image
    $scope.imageSrc=base64Data;
});

With markup:

<image ng-src="imageSrc" />