我有以下Spring 4控制器来显示数据库中的图像,并且图像在浏览器的HTML页面中正确加载,但是当我复制图像src
并将其粘贴到浏览器地址栏中时,图像不会在浏览器中打开;而是下载文本文件。如何解决这个问题?
控制器类
@RequestMapping(value = "/imageController/{imageId}")
@ResponseBody
public byte[] helloWorld(@PathVariable int imageId,HttpServletResponse response)throws Exception {
FileInfo info=commonservice.getImg(imageId);
byte[] imageInByte=null;
if(info.getImageBytes() !=null){
String ct=info.getContentType();
String[]toks=ct.split("/");
BufferedImage img = ImageIO.read(new ByteArrayInputStream(info.getImageBytes()));
if(img !=null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( img, toks[1], baos );
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
}
}
return imageInByte;
}
JSP文件
<img class="img-responsive" src="<%=request.getContextPath() %>/common/imageController/8.sjf" >
我使用过浏览器的开发人员工具,发现服务器在访问图片时会返回以下响应标头:
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Connection:Keep-Alive
Content-Disposition:attachment;filename=f.txt
Content-Length:19926
Content-Type:image/webp
Date:Tue, 10 May 2016 05:57:14 GMT
Expires:0
Keep-Alive:timeout=5, max=95
Pragma:no-cache
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
Content-Disposition
标头设置为“f.txt”,强制浏览器将图像下载为文件。我该如何改变这种行为?我已尝试response.setContentType()
并自行设置Content-Disposition
标题,但图片会一直下载为文件。