springmvc 上传文件到服务器

记录,自我学习 springmvc上传文件,图片到服务器
form表单设置  enctype="multipart/form-data"
// 新建map
		Map<String, Object> map = new HashMap<String, Object>();
// 从请求中获取到文件信息需要将请求转换为MultipartHttpServletRequest类型
		MultipartHttpServletRequest MulRequest = request instanceof MultipartHttpServletRequest
				? (MultipartHttpServletRequest) request : null;
		Iterator<String> fileNames = MulRequest.getFileNames();
		if (fileNames.hasNext()) {// 遍历请求中的图片信息
			String fileName = fileNames.next(); // 图片对应的参数名
			// log.debug("fileName:" + fileName);
			MultipartFile file = MulRequest.getFile(fileName); // 获取到图片
			String oldName = file.getOriginalFilename();// 文件原名称
			//更新时判断有没有重新选择文件
			if (oldName == null || "".equals(oldName)) {
				map.put("filepath", request.getParameter("filepath"));
				map.put("filename", request.getParameter("filename"));
				map.put("oldname", request.getParameter("oldname"));
			} else {
				String path = null;// 文件路径
				String type = null;// 文件类型
				// 判断文件类型
				type = oldName.indexOf(".") != -1 ? oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length())
						: null;
				String newFileName = String.valueOf(System.currentTimeMillis()) + "." +type;
				if (type != null) {
					//服务器路径(相对路径)存在tomcat编译项目的路径中,clean时会把上传的文件删掉
					String filepath = UploadPath.CPZXIMGSPATH;
					path = request.getSession().getServletContext().getRealPath("/") + filepath;
					File targetFile = new File(path, newFileName); // 新建文件
					if (!targetFile.exists()) { // 判断文件的路径是否存在
						targetFile.mkdirs(); // 如果文件不存在 在目录中创建文件夹

					}
					if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase())
							|| "JPG".equals(type.toUpperCase())) {
						saveFile(file, targetFile);
						// 文件名
						map.put("filepath", filepath);
						map.put("filename", newFileName);
						map.put("oldname", oldName);
					}
				}
			}
		}

/***
	 * 保存文件到服务器
		 * @param file
	 * @return
	 */
	private boolean saveFile(MultipartFile file, File targetFile) {
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				// 转存文件
				file.transferTo(targetFile);
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值