代码来源于此链接文章
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传/下载界面</title>
</head>
<body>
<div>
<form method="POST" enctype="multipart/form-data" action="/files/upload">
<table>
<tr>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="上传"/></td>
</tr>
</table>
</form>
<a href="http://localhost:8080/files/{flag}" download> 下载 </a>
</div>
</body>
</html>
package com.example.demo.demos.web;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("/files")
public class FileController {
@Value("${server.port}")
private String port;
private static final String ip = "http://localhost";
@PostMapping("/upload")
public JSONObject upload(MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
String flag = IdUtil.fastSimpleUUID();
String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + filename;
FileUtil.writeBytes(file.getBytes(), rootFilePath);
return new JSONObject().put("msg",ip + ":" + port + "/files/" + flag);
}
@GetMapping("/{flag}")
public void getFiles(@PathVariable String flag, HttpServletResponse response) {
OutputStream os;
String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";
List<String> fileNames = FileUtil.listFileNames(basePath);
String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
try {
if (StrUtil.isNotEmpty(fileName)) {
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/octet-stream");
byte[] bytes = FileUtil.readBytes(basePath + fileName);
os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();
}
} catch (Exception e) {
System.out.println("文件下载失败");
}
}
}