Spring MVC实现文件上传功能

在工作中,我们会经常使用到文件上传的功能,前一段时间,正好用到通过Spring MVC实现文件上传,特此将过程中的实现记录如下

1.在MVC的配置文件中,注入文件上传的CommonsMultipartResolver 组件,让Spring MVC支持文件上传功能

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- <property name="maxUploadSize" value="31457280"></property> -->
</bean>

可以通过maxUploadSize设置上传的最大值,但是这里我没有设置,而是写在Controller中,如果超过最大值,这样子更容易给出错误信息

2.写上传的Controller

@RequestMapping(value = "/uploadFile.rf", method = RequestMethod.POST)
@ResponseBody
public ResponseVO<String> uploadFile(HttpServletRequest request, @RequestParam("files") MultipartFile[] files) throws Exception {
	ResponseVO<String> response = new ResponseVO<String>();
	try {
		List<MultipartFile> multiFile = new ArrayList<MultipartFile>();
		String[] types = fileType.split(",");
		for (int i = 0; i < files.length; i++) {
			if (files[i].isEmpty()) {
				continue;
			}
			if(files[i].getSize() > 50* 1024 * 1024) {
				response.setStatus(ResponseVO.failCode);
				response.setMessage("单个文件大小超过50M!");
				return response;
			}
			String type = StringUtils.getExtensionName(files[i].getOriginalFilename());
			// 校验文件类型
			if (!Arrays.asList(types).contains(type)) {
				response.setStatus(ResponseVO.failCode);
				response.setMessage(type + " 暂不支持该类型文件上传");
				return response;
			}
			multiFile.add(files[i]);
	}
	if (multiFile.size() == 0) {
		response.setStatus(ResponseVO.failCode);
		response.setMessage("文件为空,请先选择文件再上传!");
		return response;
	}
	String basePath = "D:\\filepath\\tran";
	for (MultipartFile file : multiFile) {
		TimeBasedGenerator gen = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
		String uuid = gen.generate().toString();
		String orininalFileName = file.getOriginalFilename();
		String fileType = orininalFileName.substring(orininalFileName.lastIndexOf(".") + 1, orininalFileName.length());
		String resultPath = basePath + File.separator + year + File.separator + month + File.separator + uuid + "."
				+ fileType;
		File targetFile = new File(resultPath );
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		//上传到指定的位置
		file.transferTo(targetFile);
	}
	} catch (Exception e) {
		logger.error("Upload file fail,The message is:", e);
		response.setStatus(ResponseVO.failCode);
		response.setMessage("文件上传失败,请管理管理员查看失败原因.");
	}
	return response;
}

说明:
1.MultipartFile:文件对象,保存前端传递过来的文件信息
2.通过file.transferTo(targetFile),将文件上传到指定的位置

获取文件扩展名方法 StringUtil.getExtensionName

public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

至此,Spring MVC文件上传就完成了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值