因為一些原因,圖片訪問需要在項目中通過controller接口的形式訪問,做這個的時候遇到一個問題:瀏覽器單獨訪問接口時會出現(xiàn)下載圖片的現(xiàn)象,將接口鏈接放到img標簽的src中就能直接顯示。這對用戶來講是個不好的體驗,網(wǎng)上找了很多文章,都沒有說到這個,在試了很多種方法后,終于被我找到了方法,以下是代碼:
@RequestMapping("/image/test.jpg")
public void image(HttpServletResponse response){
InputStream is = null;
OutputStream os = null;
try {
response.setContentType("image/jpeg");
File file = new File("E:\\images\\test.jpg");
response.addHeader("Content-Length", "" + file.length());
is = new FileInputStream(file);
os = response.getOutputStream();
IOUtils.copy(is, os);
} catch (Exception e) {
log.error("下載圖片發(fā)生異常", e);
} finally {
try {
if (os != null) {
os.flush();
os.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
log.error("關(guān)閉流發(fā)生異常", e);
}
}
}
最主要的是要加上image/jpeg(根據(jù)文件后綴名決定,png是image/png),但是不能是image/*,否則還是會出現(xiàn)下載圖片的現(xiàn)象。其次是Content-Length(不加也可以實現(xiàn)打開圖片)