thymeleaf模板的使用方法:
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
xmlns:th="http://www.thymeleaf.org用于引入thymelaeaf模板引擎,yh是模板提供的标签,th:href用于引入外链的样式文件,th:text用于动态显示文本内容
<html lang="en" xmlns:th="http://www.thymeleaf.org">
先在配置文件当中编写文件上传的路径:
file.upload.path=D://program/Springbootstudentsystem/src/main/resources/static/
file.upload.path.relative=/static/**
创建一个MyWebAppConfigurer java文件实现WebMvcConfigurer接口, 配置资源映射路径
package com.example.springbootstudentsystem;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 资源映射路径
*/
@Configuration
public class MyWebAppConfigurer 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);
}
}
编写一个Controller类
package com.example.springbootstudentsystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@CrossOrigin
@Controller
public class test {
/**上传地址*/
@Value("${file.upload.path}")
private String filePath;
// 跳转上传页面
@RequestMapping("test")
public String test() {
return "test";
}
// 执行上传
@RequestMapping("upload")
public String upload(@RequestParam("file") MultipartFile file, Model model) {
// 获取上传文件名
String filename = file.getOriginalFilename();
// 定义上传文件保存路径
String path = filePath+"images/";
// 新建文件
File filepath = new File(path, filename);
// 判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
try {
// 写入文件
file.transferTo(new File(path + File.separator + filename));
} catch (IOException e) {
e.printStackTrace();
}
// 将src路径发送至html页面
model.addAttribute("filename", "/static/images/"+filename);
return "test";
}
}
效果如下: