使用springmvc实现文件的上传

1.spring-mvc.xml中配置文件上传文件的最大大小和编码方式
<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
		p:defaultEncoding="UTF-8">
		<property name="maxUploadSize">
			<value>104857600</value>
		</property>
		<property name="maxInMemorySize">
			<value>4096</value>
		</property>
</bean>

@RequestMapping(params = "uploadExcel")
	@ResponseBody
	public AjaxJson uploadExcel(HttpServletRequest request) {
		//从属性文件中获取上传目录
		String uploadExcel = ResourceUtil.getConfigByName("uploadExcel");
		File uploadExcelfile = new File(uploadExcel);
		//文件不存在就创建该文件夹
		if (!uploadExcelfile.exists()) {
			uploadExcelfile.mkdir();
		}
		AjaxJson j = new AjaxJson();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		if (fileMap.size() == 0) {
			j.setMsg("请选择你要上传的excel文件");
			j.setSuccess(false);
			return j;
		} else if (fileMap.size() > 1) {
			j.setMsg("一次只能上传一个文件");
			j.setSuccess(false);
			return j;
		}
		// 获取文件对象
		try {
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				MultipartFile file = entity.getValue();
				// 获取文件名称
				String fileName = file.getOriginalFilename();
				// 获取文件类型
				String extension = FilenameUtils.getExtension(fileName);
				if (extension.equals("xlsx") || extension.equals("xls")) {
					String fileUploadPath = uploadExcel + File.separator
							+ fileName;
					File file2 = new File(fileUploadPath);
					file.transferTo(file2);
					HttpSession session = request.getSession(false);
					if (session != null) {
						session.setAttribute("fileUploadPath", fileUploadPath);
					}
				} else {
					j.setMsg("请上传excel文件");
					j.setSuccess(false);
					return j;
				}
			}
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		j.setMsg("上传成功");
		j.setSuccess(true);
		return j;
	}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值