功能:
想做一个从本地获取图片,在浏览器显示图片而不是下载图片的功能
代码:
//工具类
public static void picUtils(HttpServletResponse response, String path) {
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/jpeg");
InputStream in = null;
OutputStream os = null;
try {
//读取本地图片输入流
in = new FileInputStream(path);
os = response.getOutputStream();
IOUtils.copy(in, os);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
controller:
// 国旗
@GetMapping("flags/common/100x100/{pictureId}.jpg")
public void getCountryPic(@PathVariable String pictureId, HttpServletResponse response) {
String path = userHome + "/gfx/flags/common/100x100/" + pictureId + ".jpg";
picUtils(response, path);
}
问题:
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/jpeg");
尽管设置了返回类型为jpeg图片类型,但是这两行代码不起作用
漫长的寻找原因过程……
最后,
controller参数加入:HttpServletRequest request 解决问题
public void getCountryPic(@PathVariable String pictureId, HttpServletResponse response, HttpServletRequest request)
String path = userHome + "/gfx/flags/common/100x100/" + pictureId + ".jpg";
picUtils(response, path);
}