Content Table

HttpServletResponse 返回图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@GetMapping("/image/foo.jpg")
public void enrollRegPhoto(HttpServletResponse response) {
InputStream in = null;
OutputStream out = null;

try {
response.setContentType("image/png"); // 如果是 jpg 则为 image/jpeg,svg 为 image/svg+xml 等
in = new FileInputStream("/imageDir/foo.jpg");
out = response.getOutputStream();
IOUtils.copy(in, out);
} catch (Exception ex) {
logger.warn(ex.getMessage());
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}