Controller:
@RestController
@Api(value = "文件上传下载相关接口")
@RequestMapping(value = "/file", produces = "application/json;charset=utf-8")
public class FileController {
private static final Logger log = LoggerFactory.getLogger(FileController.class);
@ApiOperation("单文件上传")
@PostMapping
public JsonResult<Void> fileUpload(MultipartFile file) throws IOException {
if (null == file) {
log.error("上传文件不能为空");
return new JsonResult<>("4", "上传文件不能为空!");
}
String fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
log.info("开始上传文件【{}】...", fileName);
FileUtils.writeByteArrayToFile(new File("d:/" + fileName), bytes);
log.info("文件【{}】上传成功...", fileName);
return new JsonResult<>();
}
@ApiOperation("多文件上传")
@PostMapping("/batch")
public JsonResult<Void> batchFileUpload(HttpServletRequest request) throws IOException {
List<MultipartFile> fileList = ((MultipartHttpServletRequest) request).getFiles("file");
for (int i = 0; i < fileList.size(); i++) {
MultipartFile file = fileList.get(i);
byte[] bytes = file.getBytes();
log.info("开始上传文件【{}】...", i);
FileUtils.writeByteArrayToFile(new File("d:/temp" + file.getOriginalFilename()), bytes);
log.info("文件【{}】上传成功...", i);
}
return new JsonResult<>();
}
@ApiOperation("文件下载")
@GetMapping("/download")
public JsonResult<Void> download(HttpServletResponse response) throws UnsupportedEncodingException {
String fileName = "干净桌面.jpg";
// 设置强制下载不打开
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"ISO-8859-1"));
// byte[] buff = new byte[1024];
BufferedInputStream bis = null;
try {
ServletOutputStream outputStream = response.getOutputStream();
byte[] buff = FileUtils.readFileToByteArray(new File("C:\\Users\\Administrator\\Pictures\\电脑桌面\\" + fileName));
outputStream.write(buff);
} catch (IOException e) {
e.printStackTrace();
}
return new JsonResult<>();
}
}
Freemarker:
<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>File</title>
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="/upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="test"/>
<input type="submit"/>
</form>
<a href="/file/download">下载test</a>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="/file/batch">
<p>文件1:<input type="file" name="file"/></p>
<p>文件2:<input type="file" name="file"/></p>
<p><input type="submit" value="上传"/></p>
</form>
</body>
</html>
配置文件application.yml:
#设置激活的环境 dev
spring:
profiles:
active: dev
#freemarker
freemarker:
template-loader-path: classpath:/templates
#设置禁用模板引擎缓存
cache: false
settings:
template_update_delay: 0
#静态文件
mvc:
static-path-pattern: /static/**
#文件上传设置
http:
multipart:
max-file-size: 100MB
max-request-size: 100MB