将 XMLhttpRequest 中的 JPG 数据放入 <img /> 标签中

put jpg data from xmlhttprequest into <img /> tag

本文关键字:img 标签 XMLhttpRequest 数据 JPG 中的      更新时间:2023-09-26

这是我代码的一部分

xmlhttp.open("GET", theUrl, true);
document.imglive.innerHTML = '<img src="data:image/jpeg,' + xmlhttp.responseText + '"/>';

这似乎不起作用。我也试过

document.imglive.src= xmlhttp.responseText;

两者都不起作用

我在这里检查了一些问题,但没有一个答案可以帮助解决这个问题。

使用 base64 来处理这些事情。在现代浏览器中,有这个btoa本机函数可以帮助您:

document.imglive.innerHTML = "<img src='data:image/jpeg;base64," + btoa(xmlhttp.responseText) + "'/>";

对于其他浏览器,有简单的模拟实现,只需查看它们即可。

PS:不要污染document对象,使用单独的变量或命名空间。

如果您对IE10+感到满意,则可以将xhr.responseType = 'blob'window.URL.createObjectURL()结合使用(以获得免费支持以获取正确的MIME类型(。

xhr.responseType = 'blob';
xhr.onload = function(response) {
  var url = window.URL.createObjectURL(response);
  document.imglive.src = url; // from your example code
}
xhr.open("GET", theUrl, true);