TOMCAT在eclipse上重新部署后就会删除之前的图片资源解决

1.首先在tomcat的server.xml 中的host 添加
 <Context docBase="F:\images"  reloadable="true"  debug="0" path="/img"/>
 添加图片映射到其余的盘符

2.修改上传的文件的代码
 


/**
	 * 上传到window环境的图片
	 */
	public static AjaxJson uploadImageWindows(MultipartFile  multipartFile,HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		InputStream is = null;
		OutputStream os = null;
		try {
			// 获取文件名称
			String originalFilename = multipartFile.getOriginalFilename();
			// 获取文件的后缀
			String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
			// 使用现在的 时间作为图片的新名称
			String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

			// 获取文件夹在Windows上的 真是文件路径 例如: upload文件夹
			//String realPath = request.getServletContext().getRealPath("img");
			String realPath ="f:/images";//真实盘符 ====>tomcat会自动映射f:/images====>img
			// 创建保存图片的文件夹
			String path = realPath + File.separator ;
			// 不存在就创建
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			// 保存文件
			file = new File(path + File.separator + fileName + suffix);

			is = multipartFile.getInputStream();
			os = new FileOutputStream(file);
			// 拷贝文件
			copyFile(is, os);
			j.setSuccess(true);
			j.setObj("img" + File.separator + fileName + suffix);//返回的图片地址
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("系统繁忙,请稍后重试");
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return j;
	}

3.访问图片的url地址
http://localhost:8080/img/20181101231837750.gif

猜你喜欢

转载自blog.csdn.net/yinlell/article/details/83659415