javascript 处理回传的二进制图像并显示在html上 100
比如转成base 64 string, 这样在html的img 的属性 src 写成 "data:image/png;base64," + base64encoded 就可以显示了。或者转成任何其他形式的数据,只要src 能认出来就可以。
环境是: nodejs+angularjs+express..... 展开
2016-02-10 · 百度知道合伙人官方认证企业
1. 发起请求页面 //ImageClient.jsp
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>ImageRequest</TITLE>
</HEAD>
<BODY>
<img src="http://127.0.0.1:8080/ImageServer.jsp"/>
</BODY>
</HTML>
2. 接受请求并返回结果页 //ImageServer.jsp
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*"%>
<%
System.out.print("enter...");
String filePath = "C:/Program Files/Tomcat/Tomcat-7.0.4/webapps/ROOT/ericsson.gif";
File file = new File(filePath);
InputStream fis;
try {
fis = new FileInputStream(file);
byte[] buf=new byte[(int)fis.available()];
fis.read(buf);
response.setContentType("application/binary;charset=ISO8859_1");
OutputStream outs = response.getOutputStream();
outs.write(buf);
outs.flush();
out.clear();
out = pageContext.pushBody();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
%>
3. 测试结果
HTML代码:
<div id="forAppend" class="demo"></div>
JS代码:
var eleAppend = document.getElementById("forAppend");
window.URL = window.URL || window.webkitURL;
if (typeof history.pushState == "function") {
var xhr = new XMLHttpRequest();
xhr.open("get", "/image/study/s/s256/mm1.jpg", true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status == 200) {
var blob = this.response;
var img = document.createElement("img");
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // 清除释放
};
img.src = window.URL.createObjectURL(blob);
eleAppend.appendChild(img);
}
}
xhr.send();
} else {
eleAppend.innerHTML = '<p style="color:#cd0000;">浏览器不给力,还是早点回去给孩子喂奶吧~</p>';
}
广告 您可能关注的内容 |