目录
文件上传
配置文件中配置文件上传相关参数
application.yml配置
#自定义属性
file:
path: D:/public/
spring:
servlet:
multipart:
#开启文件上传
enabled: true
#单个文件最大限制
max-file-size: 100MB
#单个文件最多请求文件
max-request-size: 100MB
#表示所有的访问都要经过静态资源路径
mvc:
static-path-pattern: /**
#手动加上静态资源的路径
resources:
static-locations: file:${file.path}
简单的html.页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>文件上传与下载</h1>
<form action="/file/upload" method="post" enctype="multipart/form-data">
<label>选择文件</label> <input type="file" name="file"><br>
<input type="submit" value="上传文件">
</form>
<h1><a href="/file/download">文件下载</a></h1>
</body>
</html>
文件上传upload
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${file.path}")
private String filePath;
@RequestMapping("/upload")
public String fileUpload(MultipartFile file) throws IOException {
//应该将上传的文件名修改成唯一的不重复的文件名再存储到硬盘上
//先获取原来的文件
String oldFileName = file.getOriginalFilename();
//获取文件后缀
String houZhui = oldFileName.substring(oldFileName.lastIndexOf("."));
//拼接新字符串
String newFilename = UUID.randomUUID()+houZhui;
//将文件名和路径拼接,并实例化一个对象
File uploadFile = new File(filePath+newFilename);
file.transferTo(uploadFile);
String res = "文件:" + oldFileName +"上传成功";
return res;
}
}
文件下载
文件下载其实就是文件的 copy,也就是I/O操作
@RequestMapping("/download")
public void fileDownload(HttpServletRequest request, HttpServletResponse response) {
File file = new File("d:/public/1.txt");
//设置响应头和客户端保存的文件名
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition","attachment;fileName="+file.getName());
//文件复制
try(FileInputStream in = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bin = new BufferedInputStream(in);
BufferedOutputStream bout = new BufferedOutputStream(out)) {
int len = 0;
byte[] buffer = new byte[1024];
while ((len = bin.read(buffer)) != -1) {
//输出
bout.write(buffer,0,len);
}
}catch (Exception e) {
}
}