Java上传图片到服务器路径获取系列之--图片保存到Tomcat的webapps目录下

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>
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值