Java上传图片到服务器路径获取系列之--图片保存到Tomcat的webapps目录下
note:有差错或不足之处请批评指正,谢谢!上一篇介绍了Java web项目中把客户端上传的图片保存到服务器中web工程下的指定文件夹里,但是这样存在一个弊端:因为保存图片的文件夹在项目工程文件下,所以,当项目文件更新版本的时候,就会覆盖掉原来保存图片的文件夹,造成上传文件的丢失。为了解决这个问题,进行了多方尝试,总结了以下可行方案。
1.服务端保存客户端上传的图片
(1)在Tomcat的webapps目录下创建保存上传图片的文件夹pic_file,
(2)后台获取文件夹pic_file的路径,并保存上传的图片,示例代码如下:
public static String uploadFile(MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{
Logger logger = Logger.getLogger(UploadImg.class);
if(file!=null){
//获取上传文件的原始名称
String originalFilename = file.getOriginalFilename();
String newFileName ="";
String pic_path;
// 上传图片
if ( originalFilename != null && originalFilename.length() > 0) {
//获取Tomcat服务器所在的路径
String tomcat_path = System.getProperty( "user.dir" );
System.out.println(tomcat_path);
//获取Tomcat服务器所在路径的最后一个文件目录
String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("\\")+1,tomcat_path.length());
System.out.println(bin_path);
//若最后一个文件目录为bin目录,则服务器为手动启动
if(("bin").equals(bin_path)){//手动启动Tomcat时获取路径为:D:\Software\Tomcat-8.5\bin
//获取保存上传图片的文件路径
pic_path = tomcat_path.substring(0,System.getProperty( "user.dir" ).lastIndexOf("\\")) +"\\webapps"+"\\pic_file\\";
}else{//服务中自启动Tomcat时获取路径为:D:\Software\Tomcat-8.5
pic_path = tomcat_path+"\\webapps"+"\\pic_file\\";
}
// 新的图片名称
newFileName =UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
logger.info("上传图片的路径:" + pic_path + newFileName);
// 新图片
File newFile = new File(pic_path + newFileName);
// 将内存中的数据写入磁盘
file.transferTo(newFile);
}
return newFileName;
}else{
return null;
}
}
2.客户端显示图片(1)后台获取封装显示路径
public ModelAndView GetById(int nid,HttpServletRequest request) throws SocketException {
ModelAndView mv = new ModelAndView();
mv.setViewName("jsp/pic_show_test");
Notice notice = noticeService.GetById(nid);
mv.addObject("person_name",notice.getPerson_name());
mv.addObject("title",notice.getNotice_title());
mv.addObject("content",notice.getNotice_content());
Date notice_time = notice.getNt();
mv.addObject("notice_time",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(notice_time));
//封装图片显示路径(根据当前访问的客户端请求的地址来封装)
String request_path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
String img_name = request_path + "/pic_file/"+notice.getNotice_img();
//或者直接用下面的相对路径封装
String img_name = "../pic_file/"+notice.getNotice_img();
mv.addObject("img_name",img_name); return mv;
}
(2)前端显示图片:pic_show_test.jsp页面
<div class="col-img">
<img src=${img_name} />
</div>