这里通过前端传的 path 获取图片文件实际路径并予以显示,主要还是 setContentType 设置为图片格式,让浏览器感知这是一张图片。
@RequestMapping(value = "/showImg")
public void show(String path, HttpServletRequest request, HttpServletResponse response) {response.setContentType("image/jpeg/jpg/png/gif/bmp/tiff/svg");
try {path = request.getSession().getServletContext().getRealPath("/uploads/") + path;
path = new String(path.getBytes(), "UTF-8");
File file = new File(path);
if (file.exists()) {InputStream in = new FileInputStream(path);
ServletOutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
while (in.read(b) != -1) {os.write(b);
}
in.close();
os.flush();
os.close();}
} catch (IOException e) {e.printStackTrace();
}
}