springMVC下得excel上传下载

时间:2021-01-07 23:07:54

使用springMVC的multipartfile 来做上传下载非常简单,

springMVC下得excel上传下载

springMVC的xml配置

上传
public Map<String, Object> uploadAduitExcel(MultipartFile excel, HttpServletRequest request)
throws IllegalStateException, IOException {
/* 判断文件是否为空 */
if (excel == null) {
return ResultMap.convertMap(ResultCode.PARAMETER_ERROR);
} else if (!excel.getOriginalFilename().endsWith(".xlsx")) {
return ResultMap.convertMap(ResultCode.FAIL, Prompt.bundle("file.type.error"));
}
/* 获取相对路径和设置默认文件名 */
String path = request.getSession().getServletContext().getRealPath("doc");
String fileName = Prompt.bundle("aduit.excel.name");


File targetFile = new File(path, fileName);
/* 判断目录是否存在 不存在创建 */
if (!targetFile.exists()) {
targetFile.mkdirs();
}
/* 保存文件 */
excel.transferTo(targetFile);
return ResultMap.convertMap(ResultCode.SUCCESS);
}


下载
public ResponseEntity<byte[]> downloadAduitExcel(HttpServletRequest request) throws IOException {
String path = request.getSession().getServletContext()
.getRealPath("doc" + File.separator + Prompt.bundle("aduit.excel.name"));
HttpHeaders headers = new HttpHeaders();
File file = new File(path);
if (file.exists()) {
String fileName = new String(Prompt.bundle("aduit.excel.name").getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
return new ResponseEntity<byte[]>(Prompt.bundle("aduit.excel.empty").getBytes(), headers, HttpStatus.CREATED);
}