application.properties配置
spring.thymeleaf.prefix=classpath:/templates/ #把html文件放到这个目录下面 视图前缀
spring.thymeleaf.suffix=.html #后缀名为html
spring.thymeleaf.mode=HTML5 #返回模型
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type"; content="multipart/form-data; charset=utf-8"/>
<title>Title</title>
</head>
<body>
<h1>hello springboot</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传">
</form>
<br>
<a href="/download">下载</a>
</body>
</html>
FileController
@Controller
public class FileController {
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file){
//获取文件的名字
String filename = file.getOriginalFilename();
//获取文件后缀名
String suffix = filename.substring(filename.lastIndexOf("."));
//上传的文件放在D盘下的upload文件夹中
String path="d:\\upload\\";
//防止文件名重复 随机文件名
filename=path+ UUID.randomUUID()+suffix;
File f=new File(filename);
//如果D盘下没有upload文件夹 则创建一个
if(!f.getParentFile().exists()){
f.getParentFile().mkdirs();
}
try {
//把MultipartFile转化为File类型
file.transferTo(f);
return "success";
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
@RequestMapping("/download")
public String download(HttpServletResponse response){
try {
// 文件地址,真实环境是存放在数据库中的
File file=new File("D:\\upload\\58abf51d-180c-4fcb-bed1-402ccb501e0f.jpg");
// 创建输入流,传入文件对象
FileInputStream fis=new FileInputStream(file);
// 设置相关格式
response.setContentType("application/force-download");
// 设置下载后的文件名以及header
response.addHeader("Content-disposition", "attachment;filename=123.jpg");
OutputStream os = response.getOutputStream();
// 常规操作
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.close();
fis.close();
return "success"; //为了测试方便 我写了两个html 一个是success.html还有一个是error.html 用来表示成功还是失败
}catch (IOException e){
e.printStackTrace();
return "error";
}
}
//当请求localhost:8080的时候 默认跳转到index.html页面
@RequestMapping("/")
public ModelAndView index(){
System.out.println("i am springboot");
return new ModelAndView("index");
}