前端页面:
<form action="topic/upload.html" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<button type="submit" class="btn btn-success" id="sub-btn">
<i class="glyphicon"></i> 上传
</button>
</form>
文件上传:
/**
* 文件上传
*/
@RequestMapping("/topic/upload.html")
public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("stuId") Integer stuId, HttpSession session, ModelMap modelMap) {
if(file.isEmpty()) {
modelMap.addAttribute(ManageConstraint.ATTR_NAME_MESSAGE, "上传文件失败,请重新上传");
return "system-success";
}
// 获取存储路径
String path = session.getServletContext().getRealPath(ManageConstraint.ATTR_NAME_FILE_PATH);
// 获取文件名
String fileName = file.getOriginalFilename();
// 校验后缀
String suffix = FilenameUtils.getExtension(fileName);
if(!(suffix.equals("doc") || suffix.equals("docx"))) {
modelMap.addAttribute(ManageConstraint.ATTR_NAME_MESSAGE, "上传文件失败,目前只支持附件形式为doc/docx");
return "system-success";
}
Student stu = stuService.getStudentById(stuId);
// 生成新文件名
String new_fileName = ManageUtil.getFileName(stu, suffix);
// 创建文件
File new_file = new File(path, new_fileName);
// 查看文件是否存在
if(!new_file.exists()) {
new_file.mkdir();
}
try {
file.transferTo(new_file);
} catch (IOException e) {
e.printStackTrace();
modelMap.addAttribute(ManageConstraint.ATTR_NAME_MESSAGE, "写入文件错误,请稍后再试");
return "system-success";
}
// 将文件路径和文件名存入数据库
stu.setArticleFile(path + "|" + new_fileName);
stuService.saveArticleFile(stu);
modelMap.addAttribute(ManageConstraint.ATTR_NAME_MESSAGE, "上传成功");
return "system-success";
}
/**
* 文件下载
*/
@RequestMapping("/topic/download.html/{stuId}")
public String downloadFile(@PathVariable("stuId") Integer stuId, HttpServletRequest request, HttpServletResponse response) {
Student stu = stuService.getStudentById(stuId);
String fileName = stu.getArticleFile().split("\\|")[1];
String path = request.getSession().getServletContext().getRealPath(ManageConstraint.ATTR_NAME_FILE_PATH);
response.setCharacterEncoding("UTF-8");
response.setContentType(new MimetypesFileTypeMap().getContentType(fileName));
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
File file = new File(path, fileName);
try {
InputStream in = new FileInputStream(file);
OutputStream out = response.getOutputStream();
int len = 0;
while((len = in.read()) != -1) {
out.write(len);
out.flush();
}
in.close();
out.close();
request.setAttribute(ManageConstraint.ATTR_NAME_MESSAGE, "文件下载成功");
return null;
} catch (FileNotFoundException e) {
request.setAttribute(ManageConstraint.ATTR_NAME_MESSAGE, "文件不见了,请让学生重新上传");
return "system-success";
} catch (IOException e) {
request.setAttribute(ManageConstraint.ATTR_NAME_MESSAGE, "文件下载失败,请稍后再试");
return "system-success";
}
}