在项目中有上传图片的需求,把图片上传到服务器上,然后把图片在服务器上的路径存储到数据库的路径字段中
功能需求:图片在线预览
思路:拿到图片的路径,得到该图片的输入流FileInputStream,然后通过Response得到Response的输出流OutputStream,最后把输入流写入到Response的输出流中,浏览器访问该接口即可实现图片在线预览!
//图片预览
@RequestMapping("/showImage")
@ResponseBody
public void showImage(String path, HttpServletRequest request, HttpServletResponse response) throws Exception{
response.setContentType("image/jpg");
FileInputStream fs=new FileInputStream(new File("D:\\工作\\表单电子化\\1.jpg"));
OutputStream os=response.getOutputStream();
int lenth;
byte[] bytes=new byte[1024];
while((lenth=fs.read(bytes))>0){
os.write(bytes,0,lenth);
}
fs.close();
os.close();
}
response.setContentType(“image/jpg”); 是指定图片格式,可以通过传过来的path(包括文件后缀名)得到后缀,然后动态的指定图片格式,就可以了。
new File(D:\工作\表单电子化\1.jpg") 这是写死的路径,到时候替换成传过来的path路径(服务器上的图片路径并且包括文件名和后缀名)即可。
效果