put jpg data from xmlhttprequest into <img /> tag

时光怂恿深爱的人放手 提交于 2019-12-24 00:50:20

问题


here is some part of my code

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

that don´t seem to work. i also tried

document.imglive.src= xmlhttp.responseText;

that neither worked

I checked some of the asked questions here but none of the answers where helping at this porblem.


回答1:


Use base64 for these things. In modern browsers there's this btoa native function that may help you:

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

For other browsers there are simple emulated implementations, just check them out.

P.S.: don't pollute the document object, use a separate variable or a namespace.




回答2:


If you are happy with IE10+, you can use xhr.responseType = 'blob' in conjunction with window.URL.createObjectURL() (to get free support for getting the correct mime type).

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);


来源:https://stackoverflow.com/questions/10687427/put-jpg-data-from-xmlhttprequest-into-img-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!