简单文件上传与下载

上传

配置文件

1
2
3
4
5
spring:
servlet:
multipart:
max-file-size: 300MB
max-request-size: 300MB

前端代码

1
2
3
4
5
6
7
8
9
10
11
12
<!-- class不用管!!! -->
<form action="/admin/upload" method="post" enctype="multipart/form-data" class="ui form">
<div class="required field">
<div class="ui left labeled input">
<input type="file" name="file">
</div>
</div>
<div class="ui right aligned container">
<button class="ui teal submit button">提交</button>
<button type="button" class="ui button" onclick="window.history.go(-1)">返回</button>
</div>
</form>

后端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Controller
public class UploadController {

//上传后文件保存位置
@Value("static/files")
private String fileLocation;

@PostMapping("/admin/upload")
public String upload(MultipartFile file, Model model) throws IOException {
System.out.println("进入upload");
// 获得 classpath 的绝对路径
String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;
File newFile = new File(realPath);
// 如果文件夹不存在、则新建
if (!newFile.exists()){
newFile.mkdirs();
}
// 上传
Date date = new Date();
String fileName = date.getTime() +"@" + file.getOriginalFilename();
file.transferTo(new File(newFile, fileName));
return "admin/upload";
}
}

示例

image-20211006143604933

下载

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Controller
public class UploadController {

@Value("static/files")
private String fileLocation;

@GetMapping("/admin/download")
public void download(String fileName, HttpServletResponse response) throws IOException {
System.out.println("download");
// 获得待下载文件所在文件夹的绝对路径
String realPath = ResourceUtils.getURL("classpath:").getPath() + fileLocation;

// 获得文件输入流
FileInputStream inputStream = new FileInputStream(new File(realPath, fileName));
// 设置响应头、以附件形式打开文件
response.setHeader("content-disposition", "attachment; fileName=" + fileName);
ServletOutputStream outputStream = response.getOutputStream();
int len = 0;
byte[] data = new byte[1024];
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
outputStream.close();
inputStream.close();
}
}

请求方式

http://localhost:8080/admin/download?fileName=1631839958785@13.jpg