因系统开发中需求,会有页面显示图片直接从后端获取后显示,代码如下:
后端:
/*** 获取图片流* @param response* @param fileName*/@RequestMapping(value="getImgStream",method = RequestMethod.GET)public void getImgStream(HttpServletResponse response,@RequestParam("idFile")String fileName){FileInfo fileInfo = fileService.getByName(fileName);FileInputStream fis = null;response.setContentType("image/"+fileInfo.getRealFileName().split("\\.")[1]);try {OutputStream out = response.getOutputStream();File file = new File(fileInfo.getAblatePath());fis = new FileInputStream(file);byte[] b = new byte[fis.available()];fis.read(b);out.write(b);out.flush();} catch (Exception e) {logger.error("getImgStream error",e);} finally {if (fis != null) {try {fis.close();} catch (IOException e) {logger.error("close getImgStream error",e);}}}}
前端
js文件
拼接后端API路径
img = util.getApiUrl() + '/file/getImgStream?idFile=' + item.img
Vue页面
<el-image style="height: 200px" :src="item.img" fit="contain"></el-image>