@PostMapping("/blogs/blogAdd")
public String blogAdd(HttpServletRequest request,Blog blog, @RequestParam("firstPic") MultipartFile firstPic, RedirectAttributes attributes, HttpSession session){
String message;
try{
String fileName = getFileName(4,firstPic.getOriginalFilename());
if(!firstPic.isEmpty()){
/*文件目录路径,也是服务器的虚拟路径*/
String realPath = request.getServletContext().getRealPath("/images/firstPicture");
/*由于tomcat已关闭里面的临时文件就会删除
* 所以我们还要留一手备份到项目的静态资源下,
* 如果服务器关闭重新打开,就会对项目进行重新编译,即使tomcat里的临时文件消失了,我们也照样可以访问*/
String staticPath="src/main/resources/static/images/firstPicture"; //保存到项目static资源目录下的路径
/*如果为空则创建文件*/
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}
File staticFile=new File(staticPath);
if (!staticFile.exists()){
staticFile.mkdirs();
}
File newFile = new File(file.getAbsolutePath() + File.separator + fileName);
File staticNewFile = new File(staticFile.getAbsolutePath() + File.separator + fileName);
/*复制文件到本地项目资源目录下*/
FileUtils.copyInputStreamToFile(firstPic.getInputStream(),staticNewFile);
/*上传文件*/
firstPic.transferTo(newFile);
}
blog.setFirstPicture("/images/firstPicture/"+fileName);
int blogAdd = blogService.blogAdd(blog);
message="您的数据插入成功!";
}catch (IOException ioe){
ioe.printStackTrace();
message="抱歉,您的文件资源引入有误,请重新引入!";
}catch (Exception e){
e.printStackTrace();
message="抱歉,您的数据插入失败!";
}
attributes.addFlashAttribute("message",message);
return "redirect:/admin/blogs";
}
上传完图片并不会保存到项目的/images/firstPicture 文件夹里,
而是会保存到tomcat服务器下
图片路径地址 C:\Users\你的用户名\AppData\Local\Temp\tomcat-docbase.8080.100855160746792444\images\firstPicture\文件名
/images/firstPicture 则是你访问文件时的虚拟目录的路径
String realPath = request.getServletContext().getRealPath("/images/firstPicture");
所以你可以通过/images/firstPicture/文件名 ,就可以在网站上访问你的图片路径。
但是现在又出现一个问题,即你的资源文件只是保存到服务器中的临时文件中而已, 服务器一旦关闭,所有临时文件有不见了,so 你就永远访问不到了。
我的解决办法是:
就是把文件即保存到tomcat中的临时目录 ,也保存到本地的资源目录下,但是target目录还是没有资源文件,一旦你重新开启idea,tomcat中是临时文件就没了,但是项目资源目录static下还是会有,由于你重新打开idea,进行了重新编译,所以target中的也有了资源文件,页面也可以访问到了
注意:
复制的时候不要使用transferTo(),会报错,用其他复制文件的方法,我这里用的是
FileUtils.copyInputStreamToFile()需要导入jar包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>