SpringBoot 檔案上傳與下載

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上传和下载</title>
</head>
<body>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
<p>
<label for="file1" >请选择要上传的文件</label>
<input type="file" id="file1" name="file" multiple/>
</p>
<p>
<input type="submit" value="上传">
</p>
</form>
<ul>
<li th:each="file : ${files}">
<a th:href="@{/download(fileName=${file})}" th:text="${file}"></a>
</li>
</ul>
</body>
</html>
 package com.sun.ch04.controller;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;

@Controller
public class FileController {
@GetMapping("/upload")
public String doUpload(Model model) {
// 将上传文件目录下的所有文件名列出来,保存到模型对象中
String uploadPath = "C:" + File.separator + "SpringBootUpload";
File dir = new File(uploadPath);
model.addAttribute("files", dir.list());
return "upload";
}

@PostMapping("/upload")
@ResponseBody
public String upload(HttpServletRequest request) {
// 得到所有文件的列表
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
String uploadPath = "C:" + File.separator + "SpringBootUpload";
File dir = new File(uploadPath);

// 如果保存上传文件的目录不存在,则创建它
if (!dir.exists()) {
dir.mkdirs();
}
for (MultipartFile f : files) {
if (f.isEmpty()) {
continue;
}
File target = new File(uploadPath + File.separator + f.getOriginalFilename());
try {
f.transferTo(target);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
return "文件上传成功!";
}

@GetMapping("/download")
public ResponseEntity<byte[]> download(@RequestParam String fileName) throws IOException {
String dir = "C:" + File.separator + "SpringBootUpload";
String fileFullPath = dir + File.separator + fileName;
File file = new File(fileFullPath);

ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
builder.contentLength(file.length());
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
builder.header("Content-Disposition", "attachment; filename=" + fileName);
return builder.body(FileUtils.readFileToByteArray(file));
}

}