如果默认的静态资源过滤策略不能满足开发需求,也可以自定义自定义静态资源过滤策略,自定义静态资源过滤策略有两种方式:
1.在配置文件中定义
可以在application.properties中直接定义过滤规则环日静态资源位置,代码如下:
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/
过滤规则为/static/**,静态资源位置为classpath:/static/。
重新启动项目,在浏览器中输入“http://localhost:8080/static/p1.png”,即可看到classpath:/static/目录下的资源。
2.Java编码定义
此时只需要实现WebMvcConfigurer 接口即可,然后实现该接口的addResourceHandlers方法,代码如下:
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
重新启动项目,在浏览器中输入“http://localhost:8080/static/p1.png”,即可看到classpath:/static/目录下的资源。
文件上传
单文件上传
首先创建一个SpringBoot项目并添加spring-boot-starter-web依赖。
然后在resources目录下的static目录下创建一个upload.html文件,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" value="请选择文件">
<input type="submit" value="上传文件">
</form>
</body>
</html>
这是一个很简单的文件上传页面上传接口是/upload,注意请求方法是post,enctype是multipart/form-data。
接着创建文件上传处理接口,代码如下:
@RestController
public class FileUploadController {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
@PostMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest req) {
String realPath = req.getSession().getServletContext().getRealPath("/uploadFile");
String format = sdf.format(new Date());
File folder = new File(realPath + format);
if (!folder.exists()) {
folder.mkdirs();
}
String oldName = uploadFile.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
uploadFile.transferTo(new File(folder, newName));
String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + format + newName;
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
最后在浏览器中进行测试。
运行项目,早浏览器中输入“http://localhost:8081/upload.html”进行文件上传,如图4-5所示:
单机“选择文件”按钮上传文件,文件上传上传成功后,会返回上传的访问路径,如图所示:
如果对图片上传的细节进行配置,也是允许的,代码如下:
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=D:\\temp
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false
代码解释:
- 第一行表示是否开启文件上传支持,默认为true
- 第二行表示写入磁盘的阈值,默认为0
- 第三行表示上传文件的临时保存位置
- 第四行表示上传的单个文件的最大大小,默认为1MB
- 第五行表示多文件上传时文件的总大小,默认为10MB
- 第六行表示是否延迟解析,默认为false