SpringMvc上传图片并显示,不必重启Tomcat
我在做一个新闻网站的时候,用springmvc的文件上传将新闻的图片上传至服务器端,但是每次都发现上传上去的图片,并不能显示出来,只能在重启Tomcat的情况下才能显示出上次上传的图片。当时因为自己刚刚接触SSM框架,所以也不知道是什么情况。于是,就向专业的师兄请教这个问题是怎么回事,该怎么解决。在师兄的解释下,我才恍然大悟,自己的项目在运行之前是需要先把项目打包才能发布到Tomact上面进行访问的。所以每次上传的图片上传之后,是没有被打包到项目中的,而每一次重启才将图片打包进发布的项目中。
这样做对于一个项目而言是不现实的,所以我们要找一种方法解决不用重启就能实现图片的上传与回显。所以我们需要写一个文件下载,用于需要显示图片的时候,进行图片的下载,这样一来就不需要每次上传图片就进行tomcat重启。
1.读取图片文件的的方法
接口:
public interface showPicture {
public void responseFile(HttpServletResponse response, File imageFile) throws IOException;
}
实现接口的方法:此处一定需要采用缓冲,否则文件下载会很慢,直观的体现就是,如果图片过大,就会加载很久,采用缓冲会缓解这种情况。(处理图片流时,要注意 buffer 的大小,过小会导致下载速度变慢,过大会占用较多的带宽,需要考虑平衡。)
@Component
public class showPictureImpl implements showPicture {
@Override
public void responseFile(HttpServletResponse response, File imageFile) throws IOException {
InputStream in=new FileInputStream(imageFile);
OutputStream out=response.getOutputStream();
byte [] buffer = new byte[1024];
int len=0;
while((len = in.read(buffer)) > 0){
out.write(buffer, 0, len);
}
//关闭文件输入流
in.close();
// 关闭输出流
out.close();
}
}
2:Controller层
上传图片:从前端获取文件上传的相关参数,然后得到随机的图片名称
@RequestMapping(value = "/uploadImg",method = RequestMethod.POST)
@ResponseBody
public ResponseMessage<String> uploadImg(@RequestParam("file") MultipartFile multipartFile) throws IOException {
String path= savePicture.uploadPicture(multipartFile);
System.out.println(path);
ResponseMessage<String> responseMessage = new ResponseMessage<>();
responseMessage.setCode(1000);
//将访问图片的路径,存入将要返回的对象中
responseMessage.setData("/message/show/"+path);
responseMessage.setMsg("success");
//返回json数据
return responseMessage;
}
下载图片(显示图片):以访问路径的方式得到图片的名称和后缀,并将得到的文件流返回到前端(注意看处理显示图片和下载图片的请求映射中,我用 {fileName}.{suffix} 这段代码将图片名和图片的后缀区分开,因为 GET 方式的 URL 请求地址中的 “.” 点号会被当作通配符处理掉,有多种方式可以解决。我这种方式是一种,你也可以用 “.” 转义字符来避免其通配符的作用。)
/**
* 显示图片
* @param filename
* @param suffix
* @param response
* @throws IOException
*/
@RequestMapping("/show/{filename}.{suffix}")
public void showPicture(@PathVariable("filename") String filename,
@PathVariable("suffix") String suffix,
HttpServletResponse response) throws IOException {
File imagefile=new File(picturePath.path+filename+"."+suffix);
showPictures.responseFile(response,imagefile);
}
3:防止图片重名的情况,在上传图片的时候,就随机对图片随机命名
上传的原始文件名存在命名冲突的问题,为了避免文件名冲突被覆盖,我们可以使用 UUID 来生成唯一的文件名
public class savePicture {
public static String uploadPicture(MultipartFile file){
if (file!=null){
String fileName=file.getOriginalFilename();
String suffix=fileName.substring(fileName.lastIndexOf("."));
String newFileName= UUID.randomUUID().toString()+suffix;
String filePath=picturePath.path+newFileName;
newFileName="image/"+newFileName;//返回图片访问路径
File save=new File(filePath);
try{
file.transferTo(save);
}catch (Exception e ){
e.printStackTrace();
}
return newFileName;
}
return null;
}
}