前台:
<img src="'/name/getPic?picName='+ picPath">
后台:
1.在SpringBootApplication启动类中添加如下方法,配饰访问路径
@Bean
public ServletRegistrationBean getServletRegistrationBean() {
ServletRegistrationBean bean = new ServletRegistrationBean(new GetPic());
bean.addUrlMappings("/getPic");
return bean;
}
2.新建类,去把图片以流的形式写回页面
public class GetPic extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String picName=request.getParameter("picName").toString();
File f = null;
f = new File(picName);
if (f.exists()) {
tofile(f, response, "image/jpg");
}
}
public void tofile(File file, HttpServletResponse response, String contentType){
try {
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[(int) in.available()];
in.read(buf);
response.setContentType(contentType);
OutputStream toClient = response.getOutputStream();
toClient.write(buf);
toClient.flush();
toClient.close();
in.close();
} catch (Exception e) {
}
}
}