Angular JS - 请求以获取图像 [英] Angular JS - request in order to get an image
问题描述
我想在 UI 上显示 jpeg 图像.为此,我请求我的服务(GET 方法),然后转换为 base 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('text/plain; charset = x-user-defined') 创建一个 XMLHttpRequest 并且它有效:
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 (XMLHttpRequest) 标准,你可以使用普通的 Angular 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?)");
});
这篇关于Angular JS - 请求以获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!