springboot限制文件上传类型
时间: 2023-07-06 19:34:08 浏览: 76
在Spring Boot中,限制文件上传类型可以通过以下步骤实现:
1. 在application.properties或application.yml中添加以下配置:
```
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=200KB
spring.servlet.multipart.max-request-size=215KB
```
其中,file-size-threshold是一个临时文件的大小阈值,max-file-size是最大文件大小的限制,max-request-size是整个请求的最大大小限制。
2. 创建一个自定义的MultipartResolver,重写isMultipart方法:
```java
public class CustomMultipartResolver extends CommonsMultipartResolver {
private static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/png");
@Override
public boolean isMultipart(HttpServletRequest request) {
final String contentType = request.getContentType();
if (contentType != null && !contentType.isEmpty()) {
return ALLOWED_CONTENT_TYPES.contains(contentType.toLowerCase());
}
return false;
}
}
```
在这个例子中,只允许上传JPEG和PNG格式的文件。如果上传的文件类型不在ALLOWED_CONTENT_TYPES中,则不允许上传。
3. 在Spring Boot应用程序的@Configuration类中,添加以下bean:
```java
@Bean
public MultipartResolver multipartResolver() {
return new CustomMultipartResolver();
}
```
这样就完成了文件上传类型的限制。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)