【发布时间】:2019-07-30 14:03:49
【问题描述】:
在显示来自 REST API 的 b64 编码 png 图像响应时,我的图像图标已损坏。
javascript-
function getcap(){
var http = new XMLHttpRequest()
http.open("GET", "http://localhost:8888/newcaptcha",true)
http.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
http.setRequestHeader("Access-Control-Allow-Origin", "http://localhost:8888");
http.send()
http.onload = () => {
var resp=unescape(encodeURIComponent(http.responseText));
var b64Response = window.btoa(resp);
console.log('data:image/png;base64,'+b64Response);
document.getElementById("capimg").src = 'data:image/png;base64,'+b64Response;
}
}
html -
<div id="newCaptcha" onClick="getcap()" ><h5>new captcha:</h5><img id="capimg" width="30" height ="30"/></div>
服务器代码 -
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value = "/newcaptcha", method = RequestMethod.GET, produces = "image/png")
public @ResponseBody byte[] getnewCaptcha() {
try {
Random random = new Random();
imgkey= random.nextInt(3);
InputStream is = this.getClass().getResourceAsStream("/"+captcheMap.get(imgkey)+".png");
BufferedImage img = ImageIO.read(is);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ImageIO.write(img, "png", bao);
return bao.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
【问题讨论】:
-
你从“resp”值中得到什么?
-
服务器呢? base64代码是如何生成的?
-
@luca.vercelli 服务器产生响应“image/png”并返回一个字节数组。
-
所以,您的网络服务器返回的是图像,而不是图像 b64……为什么要对它进行编码?你不能把图片放到你的IMG标签里吗?类似
document.getElementById("capimg").src = "./newcaptcha"
标签: javascript java html spring rest