一、上传文件
@RequestMapping(value="/upfile", method = RequestMethod.POST)
public ResultVo uploadFile(@RequestParam MultipartFile file,HttpServletRequest request) throws Exception{
if(file==null)
return ResultVo.error("1", "上传文件不能为空");
String fileName = file.getOriginalFilename();
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
return ResultVo.error("1", "上传文件格式错误,请上传后缀为.xls或.xlsx的文件");
}
String filePath = request.getSession().getServletContext().getRealPath("upload/");
String path = filePath+fileName;
try {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
out.write(file.getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
ResultVo.error("1", "上传失败");
}
return ResultVo.success();
}
二、下载文件
@RequestMapping(value = "/downtemp", method = RequestMethod.GET)
public void downloadTemp(HttpServletRequest request,HttpServletResponse response) {
String fileNames ="导入模板.xls";
logger.debug("下载模板文件名称:"+fileNames);
try {
InputStream fis = FileController.class.getResourceAsStream("/templates/导入模板.xls");
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.setContentType("bin");
String agent = request.getHeader("USER-AGENT");
String codedfilename = "";
if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {// ie
String name = java.net.URLEncoder.encode(fileNames, "UTF8");
codedfilename = name;
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
}
response.addHeader("Content-Disposition", "attachment; filename=\"" + codedfilename + "\"");
response.getOutputStream().write(buffer);
} catch (IOException e) {
e.printStackTrace();
logger.error("下载模板文件报错"+e.getMessage(), e);
}
}
模板文件存放位置:
/src/main/resources/templates/导入模板.xls