角JS - 为了得到一个图像请求 [英] Angular JS - request in order to get an image

查看:138
本文介绍了角JS - 为了得到一个图像请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示在UI JPEG图像。对于这一点,我要求我的服务(GET方法),然后我转换为基础64:

I would like to display a jpeg image on UI. For this, I request my service (GET method) and then I converted to base 64:

$http({ 
    url: "...",
    method: "GET",
    headers: {'Content-Type': 'image/jpeg'}             
}).then(function(dataImage){
    var binary = '';
    var responseText = dataImage.data;
    var responseTextLen = dataImage.data.length;
    for (var j = 0; j < responseTextLen; j+=1) {
         binary += String.fromCharCode(responseText.charCodeAt(j) & 0xff)
    }
    base64Image = 'data:image/jpeg;base64,' + window.btoa(binary);
});  

在结束时,我的浏览器告诉我,图像已损坏或截断。
所以我试图用一个overrideMimeType创建XMLHtt prequest('text / plain的;字符集= X-用户自定义)和它的作品:

In the end, my browser tells me that the image is corrupt or truncated. So I tried creating a XMLHttpRequest using a overrideMimeType('text / plain; charset = x-user-defined') and it works:

var xhr_object = new XMLHttpRequest();
xhr_object.overrideMimeType('text/plain; charset=x-user-defined');
xhr_object.open('GET', '...', false);
xhr_object.send(null);
if(xhr_object.status == 200){
    var responseText = xhr_object.responseText;
    var responseTextLen = responseText.length;
    var binary = ''
    for (var j = 0; j < responseTextLen; j+=1) {
        binary += String.fromCharCode(responseText.charCodeAt(j) & 0xff)
    }   
    base64Image = 'data:image/jpeg;base64,' + window.btoa(binary);
}

有什么区别?

推荐答案

现在AngularJS尊重XHR(XMLHtt prequest)的标准,你可以使用普通的角JS的 $ HTTP 结合HTML的的FileReader

Now AngularJS respects the XHR (XMLHttpRequest) standard and you can use plain angular JS $http combined with the HTML FileReader.

关键是要获取数据作为传递给读者一个blob。

The trick is to get the data as a blob which you pass to the reader.

var url = 'http://'; // enter url here
$http.get(url,{responseType: "blob"}).
    success(function(data, status, headers, config) {
        // encode data to base 64 url
        fr = new FileReader();
        fr.onload = function(){
            // this variable holds your base64 image data URI (string)
            // use readAsBinary() or readAsBinaryString() below to obtain other data types
            console.log( fr.result );
        };
        fr.readAsDataURL(data);
    }).
    error(function(data, status, headers, config) {
        alert("The url could not be loaded...\n (network error? non-valid url? server offline? etc?)");
    });

这篇关于角JS - 为了得到一个图像请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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