今天接受的任务是从数据库获取的图片地址,使用io流将图片展示出来,我在数据库查的数据中只有该记录的绝对路径,我需要将该图片展示在页面上,但是项目是springboot的项目,在img标签的src不能使用绝对路径,只能请求后台接口将这个绝对路径的图片文件展示出来
前端代码
<div > <img id="demo1" style=" width: 60%;"> </div>
js代码
$('#demo1').attr('src','/device/IoReadImage?imgName='+'d:/saye/QRcode/20191119135741JAaD.png');
java后台代码
@RequestMapping(value = "/device/IoReadImage")
public String IoReadImage(String imgName,HttpServletRequest request,HttpServletResponse response) throws IOException {
ServletOutputStream out = null;
FileInputStream ips = null;
try {
//获取图片存放路径
String imgPath =imgName;
ips = new FileInputStream(new File(imgPath));
response.setContentType("multipart/form-data");
out = response.getOutputStream();
//读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = ips.read(buffer)) != -1){
out.write(buffer,0,len);
}
out.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
out.close();
ips.close();
}
return null;
}