1 文件上传
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" value="上传文件"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
controller
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String path = ClassUtils.getDefaultClassLoader().getResource("templates/").getPath();
File dest = new File(path + fileName);
if (!dest.exists()){
dest.mkdir();
}
file.transferTo(dest);
return "ok";
}
2 文件下载
@RequestMapping("/download")
@ResponseBody
public String download(HttpServletResponse response) {
String path = ClassUtils.getDefaultClassLoader().getResource("templates/").getPath();
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=hzj.sql");
FileInputStream inputStream = null;
ServletOutputStream outputStream = null;
try {
inputStream = new FileInputStream(new File(path + "hzj.sql"));
outputStream = response.getOutputStream();
byte[] b = new byte[1024];
while (inputStream.read(b) != -1){
outputStream.write(b);
outputStream.flush();
}
} catch (IOException e){
e.printStackTrace();
} finally {
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "ok";
}