今天遇到了一个问题,后台拿到图片流之后,怎么在页面上展示。
在这里贴出实现代码
其中参考了https://www.cnblogs.com/cdemo/p/5225848.html,这篇博客,表示感谢。
整理了一下自己的代码,供大家参考
后台代码
@RequestMapping(value = "getImg")
public void getImg(HttpServletResponse response) {
String fileName = "name.png";
ByteArrayOutputStream stream = 图片流;
OutputStream toClient = null;
try {
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition","attachment;filename=" + fileName);
toClient = response.getOutputStream();
toClient.write(stream.toByteArray());
toClient.flush();
toClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
前端JS
function make(){
var url = "${ctx}/product/configure/productInfo/getImg";
var xhr = new XMLHttpRequest();
xhr.open("get", url, 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);
$("#maked").html(img);
}
};
xhr.send();
}
HTML标签
<tr>
<td style="text-decoration: none;text-align:center">
<input type="button" value="生成新的图片" οnclick="make();" />
</td>
<td colspan="3" style="text-decoration: none;text-align:center">
<div id="maked">
</div>
</td>
</tr>
虽然后来没有使用这种方法,但不失为一次学习的机会。学习了