我试图在img标签中显示一个带有以下代码的图片,但是在浏览器控制台上显示404文件未找到错误。
Jsp Page:
<img id="img" src="logo.jsp?path=${schoolModel.user_name}" style="width:105px; height:120px;"/>
logo.jsp:
<%@page import="com.slv.CommonUtils.WebSLCMConstants"%>
<%@page import="java.io.BufferedOutputStream"%>
<%@page import="java.io.BufferedInputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>
<%@page import="java.io.InputStream"%>
<%
File f=null;
try {
System.out.println("Inside");
String path=request.getParameter("path");
if(path.equals("")){
f=new File(WebSLCMConstants.img_retrieve_path+"WebSLCM/no_image.jpg");
} else {
f=new File(WebSLCMConstants.img_retrieve_path+path);
}
String str=f.toString();
response.setContentType("image/jpg");
ServletOutputStream sos;
FileInputStream fin = new FileInputStream(str);
BufferedInputStream bin = new BufferedInputStream(fin);
sos = response.getOutputStream();
BufferedOutputStream bout = new BufferedOutputStream(sos);
int ch =0;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
if (true) return;
}
catch (Exception e)
{
e.printStackTrace();
}
%>
在GUI浏览器控制台上显示404文件未找到错误,如下所示:
] 1
答案 0 :(得分:0)
JSP页面
<img id="img" src="image.do?path=yourPath" style="width:105px; height:120px;"/>
控制器类:
@RequestMapping(value = "/image.do", method = RequestMethod.GET)
public ResponseEntity getImage(String path, HttpServletResponse response) {
try {
if (StringUtils.isEmpty(path)) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
} else {
response.setHeader("Content-Type", "image/jpg");
FileInputStream fin = new FileInputStream(path);
ServletOutputStream out = response.getOutputStream();
IOUtils.copy(fin, out);
IOUtils.closeQuietly(fin);
response.flushBuffer();
return new ResponseEntity(HttpStatus.OK);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}