base64编码图片不显示

base64 encoded image not displaying

所以我正在测试我的代码,看看我上传的图片是否成功转换为 base64。但是,当我执行 alert(data) 时,我发现它是一堆乱码的未知字符。我想让弹出消息包含 base64 字符串,这样我就可以将其放入在线 base64 解码器中,以确认上传的图像是否正确。

之后,我想将文件名 + base64 字符串提供给我的 php 脚本,然后将其写入服务器。

然而这就是我得到的

http://i.imgur.com/LhqdNxv.png

这是应该获取给定图像并进行转换的代码。

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

//
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);
    }
}]);

读成BinaryString肯定会给您带来无法打印的字符。如果您希望它作为 base64 编码(特别是显示为图像),那么您需要将其读取为 DataURL。以下一定对您有帮助:

r.readAsDataURL(f);

有关 FileReader 的更多信息,请参阅 MDN docs

这里正在 fiddle 尝试不同的读取类型。