文件上传
1.创建提交表单
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/user/upload" method="post" enctype="multipart/form-data">
<label>账号:</label><input type="text" name="username">
<label>照片:</label><input type="file" name="upload">
<input type="submit" value="提交">
</form>
</body>
</html>
- 添加控制器处理上传的文件信息
@RestController
@RequestMapping("user")
public class UserContorller {
@RequestMapping("upload")
public String upolad(MultipartFile upload, String username) throws IOException {
System.out.println("username" + username + "文件名称" +upload.getOriginalFilename());
upload.transferTo(new File("d:/",upload.getOriginalFilename()));
return "success..";
}
}
2.配置相关的上传参数
spring.servlet.multipart.enabled=true
#文件上传大小
spring.servlet.multipart.max-file-size=200MB
# 设置文件一次上传的文件总大小
spring.servlet.multipart.max-request-size=200MB
文件下载
1.页面提供下载按钮
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<form action="/user/upload" method="post" enctype="multipart/form-data">
<label>账号:</label><input type="text" name="username">
<label>照片:</label><input type="file" name="upload">
<input type="submit" value="提交">
</form>
</body>
<h2>
<a href="/user/download">文件下载</a>
</h2>
</html>
2.服务端处理下载请求
@RequestMapping("download")
public void downloadFile(HttpServletRequest request , HttpServletResponse response) {
File file = new File("D:\\Documents\\1.jpg");
//设置响应头和客户端保存文件名
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
FileInputStream in = null;
ServletOutputStream out = null;
try {
//文件复制
in = new FileInputStream(file);
out = response.getOutputStream();
byte[] b = new byte[1024];
int lenth = 0;
while ((lenth = in.read(b)) >0){
out.write(b,0,lenth);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}