Zypps987
Zypps987

Reputation: 414

base64 encoded image not displaying

So I was testing my code to see if my uploaded image was converted to base64 successfully. When I did alert(data) however I found that it was a garbled mess of unknown characters. I wanted to have the popup message contain the base64 string so I could put it into an online base64 decoder to confirm that the uploaded image was correct.

Afterwards I want to give the file name + base64 string to my php script which then writes it to the server.

However this is what I got

https://i.sstatic.net/089Gq.png

Here is the code that is supposed to take the given image and convert it.

var app = angular.module("app", ["ui.bootstrap"]);

//http://stackoverflow.com/questions/18571001/file-upload-using-angularjs
app.factory('API', function ($http) {   
    return {
    uploadImage: function (image) {
        return $http.post('/js/upload.php', image);
    }
    }
});

app.controller('MainController',['$scope', '$http', 'API', function($scope, $http, API) {
    $scope.imageUrl = "";
    $scope.template = "";
    $scope.templates = [];

    $scope.templates.push("select an option...");
    $scope.templates.push("MakeGray");
    $scope.templates.push("Canny");
    $scope.templates.push("HSV");

    $scope.template = $scope.templates[0];

    $scope.add = function() {

    var f = document.getElementById('fileToUpload').files[0];  // name of image
    var files = document.getElementById('fileToUpload').files;
    var r = new FileReader();

    r.onload = function(event){
        console.log(event.target.result);
    }

    r.onloadend = function(e) {

        var data = e.target.result;
        alert(data);

        var formData = new FormData();

        formData.append("fileToUpload", f,f.name);

        API.uploadImage(formData)
        .success(function (imgUrl) {
            $scope.imageUrl = imgUrl;
        })
        .error (function (error) {
        });
    }

    r.readAsBinaryString(f);
    }
}]);

Upvotes: 0

Views: 1095

Answers (1)

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

Reading as BinaryString is sure to give you unprintable characters. If you want it as base64 encoded (specifically to display as image) then you need to read it as DataURL. Following will definitely help you:

r.readAsDataURL(f);

For more information on FileReader consult MDN docs.

Here is working fiddle to play with different read types.

Upvotes: 2

Related Questions