在HTML显示图像,该图像是从Ajax调用返回的MIME媒体类型 [英] Display image in html which is returned as a MIME media type from an ajax call
问题描述
我想显示PNG格式的图像(它返回一个MIME媒体类型的图像/ PNG从以下code)。是否需要以某种方式保存:
$。阿贾克斯({
键入:GET,
网址:网址+/ API /图片/,
的contentType:图像/ PNG,
异步:假的
})
.done(函数(MSG){
//味精是MIME媒体类型的PNG图像
//如何显示此图像内的HTML页面?
})
.fail(函数(MSG){
//失败是正常的形象,只是忽略它
});
下面是一个使用纯Java脚本(小提琴一的解决方案>)
HTML
< DIV的风格=背景颜色:#4679bd;填充:.5em;>
< IMG ID =形象/>
< / DIV>
Javascript的
VAR请求=新XMLHtt prequest();
request.open(GET,HTTP://fiddle.jshell.net/img/logo.png,真正的);
request.responseType ='arraybuffer';
request.onload =功能(E){
VAR数据=新Uint8Array(this.response);
VAR生= String.fromChar code.apply(空,数据);
VAR的base64 = BTOA(生);
变种SRC =数据:图像/ JPEG; BASE64,+ BASE64;
。的document.getElementById(图像)SRC = SRC;
};
request.send();
它使用一个 Uint8Array 和 responseType
XMLHtt prequest 2级,让您的跨浏览器的里程可能会有所不同。我只在最近版本的Firefox和Chrome的测试。
至于jQuery的解决方案去,我发现了很多讨论有的<一HREF =https://gist.github.com/SaneMethod/7548768相对=nofollow>扩展的,但没有任何官方为止。
I'm trying to display an image in PNG format (it is returned as a MIME media type image/png from the following code). Does it need to be saved somehow?:
$.ajax({
type: "GET",
url: url + "/api/image/",
contentType: "image/png",
async: false
})
.done(function(msg) {
// msg IS THE MIME MEDIA TYPE PNG IMAGE
// HOW DO I DISPLAY THIS IMAGE INSIDE AN HTML PAGE?
})
.fail(function(msg) {
// failing is okay for image, just ignore it
});
Here's a solution using pure Javascript (fiddle):
HTML
<div style="background-color: #4679bd; padding: .5em;">
<img id="image"/>
</div>
Javascript
var request = new XMLHttpRequest();
request.open('GET','http://fiddle.jshell.net/img/logo.png', true);
request.responseType = 'arraybuffer';
request.onload = function(e) {
var data = new Uint8Array(this.response);
var raw = String.fromCharCode.apply(null, data);
var base64 = btoa(raw);
var src = "data:image/jpeg;base64," + base64;
document.getElementById("image").src = src;
};
request.send();
It uses a Uint8Array and the responseType
property of XMLHttpRequest Level 2, so your cross-browser mileage may vary. I've only tested in a recent version of Firefox and Chrome.
As far as a JQuery solution goes, I found a lot of discussion and some extensions, but nothing "official" so far.
这篇关于在HTML显示图像,该图像是从Ajax调用返回的MIME媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!