实现步骤
设置上传文件路径application.yml
编写文件上传配置类MyWebConfig
前端页面编写upload.html
后端业务实现TestController
效果展示
application.yml
file.upload.path=E:/idea2020/project/springbootlearn/springboot-01-thymeleaf/src/main/resources/static/images
file.upload.path.relative=/images/*
MyWebConfig
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
//上传地址
@Value("${file.upload.path}")
private String filePath;
//显示相对地址
@Value("${file.upload.path.relative}")
private String fileRelativePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(fileRelativePath).addResourceLocations("file:/"+filePath);
}
}
upload.html
<!DOCTYPE html>
<!--<html lang="en"xmlns:th="http://www.thymeleaf.org">-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>upload</title>
<style>
div{
width: 400px;
height: 30px;
border: 1px gainsboro;
margin-top: 50px;
margin-left: 40%;
}
.images{
margin-left: 40%;
background-color: lightcyan;
}
</style>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<div class="first">
<input type="file" name="fileName" >
<input type="submit" value="上传" >
</div>
</form>
<div class="images">
<p>上传图片名:[[${fileName}]]</p>
<p>图片显示:</p>
<img th:src="@{${fileName}}" alt="">
</div>
</body>
</html>
TestController
@Controller
public class TestController {
//上传地址
@Value("${file.upload.path}")
private String filePath;
@RequestMapping("/test")
public String test(){
return "upload";
}
//后端代码实现
@RequestMapping("/upload")
public String upload(@RequestParam("fileName")MultipartFile file, Model model){
//获取上传文件名
String filename = file.getOriginalFilename();
//定义文件保存路径
String path = filePath + "/file/";
//新建文件
File filepath = new File(path, filename);
//判断路径是肉存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()){
filepath.getParentFile().mkdir();
}
//写入文件
try {
file.transferTo(new File(path+File.separator+filename));
} catch (IOException e) {
e.printStackTrace();
}
model.addAttribute("fileName","/images/file/"+filename);
return "upload";
}
}
效果展示