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;
}