Spring MVC 学习笔记 5《5.2 多文件上传》

接着上一篇,添加多文件支持

/ssm/src/main/java/com/jerry/ssm/controller/UpLoadController.java 和上图一样也在这个控制器里,只是这里分开列,方便查看
文件上传界面 http://localhost/goUploadFile.html
单文件上传接口 http://localhost/uploadFile
多文件上传接口 http://localhost/uploadFiles

	。。。
	/**
	 * 文件上传界面
	 * http://localhost/goUploadFile.html
	 * @throws JerryException 
	 */
	@RequestMapping("/goUploadFile.html")
	public String goUploadFile() throws JerryException {
		return "goUploadFile";
	}
	
	/**
	 * 文件上传接口
	 * http://localhost/uploadFile
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/uploadFile", produces={"application/json; charset=UTF-8"})
	public Map<String, String> uploadFile(Integer refType, Long refId, String remark, @RequestParam("uploadfile") CommonsMultipartFile file, HttpServletRequest request) {
		return uploadFile(refType, file, request);
	}
	
	/**
	 * 文件批量上传接口
	 * http://localhost/uploadFiles
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/uploadFiles", produces={"application/json; charset=UTF-8"})
	public Map<String, Object> uploadFiles(Integer refType, Long refId, String remark, @RequestParam("uploadfile") CommonsMultipartFile[] files, HttpServletRequest request) {
		Map<String , Object> resultMap = new HashMap<String, Object>();
		
		for (int i = 0; i < files.length; i++) {
			resultMap.put("file"+(i+1) , uploadFile(refType, files[i], request));
		}
		
		return resultMap;
	}

	private Map<String, String> uploadFile(Integer refType, CommonsMultipartFile file, HttpServletRequest request) {
		Map<String , String> resultMap = new HashMap<String ,String>();
		// ============================ 存储文件到服务器硬盘 ============================
		// --------------- 后端校验 开始 ---------------
		if(file.isEmpty()){
			resultMap.put("code", "1000");
			resultMap.put("msg", "请选择上传文件");
			return resultMap;
		}
		// 扩展名校验
		String suffix = "";
		try {
			suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// 从原文件名中截取出扩展名
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", "1001");
			resultMap.put("msg", "扩展名错误");
			return resultMap;
		}
		// --------------- 后端校验 结束 ---------------
		
		// ------------ 生成文件名  ------------
		// 图片类型_UUID_时间戳.扩展名
 		String fileName= refType + "_" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + suffix;
		
		// ------------ 确定保存位置  ------------
		// 从配置文件读取绝对路径
		String diskPath = "file" + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date());
		// 用于展示的url虚拟路径
		String urlPath = diskPath.replace("\\", "/");
		// 生成保存路径
		File filePath = new File(PropertiesUtils.get("upload_path) + diskPath);
		if(!filePath.exists()){// 如果不存在就创建
			try {
				filePath.mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
				resultMap.put("code", "2001");
				resultMap.put("msg", "创建保存路径失败");
				return resultMap;
			}
		}
		
		// ------------ 保存文件 ------------
		try {
			// filePath + fileName = 完整文件路径
			//file.transferTo(new File(filePath, fileName));
			// 保存上传的文件到硬盘
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath, fileName));
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", "4001");
			resultMap.put("msg", "文件保存失败");
			return resultMap;
		}
		
		//将上传记录存储到数据库记录表中(用户ID,上传文件原始名,上传文件新名,时间,文件类型)
		int i = 1; // 保存文件信息到数据库,返回成功标识(这一步本Demo就省了);
		
		// 返回结果给客户端
		if(i > 0){
			resultMap.put("code", "1000");
			resultMap.put("msg", "文件上传成功");
			resultMap.put("fileName", file.getOriginalFilename());
			resultMap.put("url", urlPath + "/" + fileName);
			resultMap.put("fullUrl", request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ "/" + urlPath + "/" + fileName);
		}else{
			resultMap.put("code", "4000");
			resultMap.put("msg", "文件上传失败");
		}			
		return resultMap;
	}

添加JSP 文件上传界面

/ssm/src/main/webapp/WEB-INF/jsp/goUploadFile.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<title>SpringMVC 文件上传 Demo</title>
	</head>
	<body>
		<h1>SpringMVC 单文件上传 Demo</h1>
		<form action="uploadFile" method="post" enctype="multipart/form-data">
			文件归属对象类型:<input type="text" name="refType"  value=""/><br />
			文件归属对象id:<input type="text" name="refId"  value=""/><br />
			文件描述:<input type="text" name="remark"  value=""/><br />
			文件:<input type="file" name="uploadfile" /><br />
			<input type="submit" value="点击上传" />		
		</form>
		
		<h1>SpringMVC 多文件上传 Demo</h1>
		<form action="uploadFiles" method="post" enctype="multipart/form-data">
			文件归属对象类型:<input type="text" name="refType"  value=""/><br />
			文件归属对象id:<input type="text" name="refId"  value=""/><br />
			文件描述:<input type="text" name="remark"  value=""/><br />
			文件1:<input type="file" name="uploadfile" /><br />
			文件2:<input type="file" name="uploadfile" /><br />
			文件3:<input type="file" name="uploadfile" /><br />
			<input type="submit" value="批量上传" />		
		</form>
		
	</body>
</html>

甩锅说明

实现多文件的关键是 CommonsMultipartFile[] files 但是我暴力的用for遍历单个上传函数的方式,肯定是有待优化的。

扩展学习

用Java Servlet3.0 的 Part 实现单文件和多文件上传。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑虾

多情黯叹痴情癫。情癫苦笑多情难

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值