使用angularjs在html中显示blob图像 [英] Display blob image in html with angularjs

查看:474
本文介绍了使用angularjs在html中显示blob图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些图像以blob的形式存储在mysql数据库中.我想将其显示为html.我从服务器收到这样的响应:

I have some images stored as blob in mysql database. I want to display it in html. I get the response from the server like this:

{"data":[{"ClassImage":{"type":"Buffer","data":[91,111,98,106,101,99,116,32,70,105,108,101,93]}}],"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"http://192.168.1.19:80/getImage","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}

我真的不知道我在做什么.搜索之后,我发现必须将Blob响应转换为base64,然后为图像创建一个临时URL,并使用它为图像设置src.

I don't really know what I'm doing. AFter searching I found that I have to convert the blob response to base64 and then create a temporary url for the image and use it to set the src for the image.

当我将responseType设置为blob时,响应的数据部分为空({}).当我未设置任何响应类型时,我将其获取为[91,111,98,106,101,99,116,32,70,105,108,101,93].

When I set the responseType to blob, the data part of the response is empty({}). When I don't set any response type I get it as [91,111,98,106,101,99,116,32,70,105,108,101,93].

这是代码:

$scope.getImage = function(){
        $http({
            method:'GET',
            url: $scope.ipForHttp+"getImage"
            // responseType:'arrayBuffer'
        })
        .then(function(response){
            var u8 = new Uint8Array(response.data[0].ClassImage.data);
            var b64encoded = btoa(String.fromCharCode.apply(null, u8));
            var file = new Blob(u8, {type: 'image/png'});
             $scope.fileURL = URL.createObjectURL(file);
             $scope.content = $sce.trustAsResourceUrl($scope.fileURL);

            console.log($scope.fileURL);
            console.log(JSON.stringify(response));
        })
    }

html:

        <div>
            Image:
            <!-- <img ng-src="{{content}}"> -->
            <!-- <img data-ng-src="data:image/png;base64,{{b64encoded}}"> -->
            <img ng-src="{{fileURL}}">
            <p>{{fileURL}}</p>
        </div>

createObjectURL之后得到的fileURLblob:http://192.168.1.19/6d5ab92f-7e86-4537-893c-f22826ed1b5a

当我这样做时,我没有得到图像.当我转到url时,该页面为空白.我在做什么错了?

When I do this I don't get the image. When I go to the url the page is blank. What am I doing wrong?

推荐答案

我只需要将响应转换为base64并显示出来即可.

I just had to convert the response to base64 and display it.

$scope.getImage = function(){
    $http({
      method:'GET',
      url: $scope.ipForHttp+"getImage"
            // responseType:'arrayBuffer'
        })
   .then(function(response){

      $scope.b64encoded = btoa(String.fromCharCode.apply(null, response.data[0].ClassImage.data));

        })
    }

在html中:

<img data-ng-src="data:image/png;base64,{{b64encoded}}">

这篇关于使用angularjs在html中显示blob图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆