springboot multipartfile 拦截器
时间: 2023-07-08 18:48:39 浏览: 140
Spring Boot 中可以通过编写拦截器来对上传的文件进行拦截和处理。拦截器是在请求进入 Controller 前执行的,因此可以在拦截器中对上传的文件进行检查和处理。
以下是一个示例拦截器的代码,可以限制上传的文件大小和文件类型:
```java
@Component
public class FileUploadInterceptor implements HandlerInterceptor {
private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
private static final List<String> ALLOWED_TYPES = Arrays.asList("image/jpeg", "image/png", "image/gif");
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getMethod().equalsIgnoreCase("POST")) {
Collection<Part> parts = request.getParts();
for (Part part : parts) {
if (part instanceof Part) {
MultipartFile file = new StandardMultipartHttpServletRequest(request).getFile(part.getName());
if (file != null) {
if (file.getSize() > MAX_FILE_SIZE) {
throw new ServletException("File size exceeds limit");
}
if (!ALLOWED_TYPES.contains(file.getContentType())) {
throw new ServletException("Invalid file type");
}
}
}
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// Post-processing code goes here
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// Cleanup code goes here
}
}
```
在上面的代码中,我们定义了一个 `FileUploadInterceptor` 拦截器,它会在请求进入 Controller 前对 HTTP POST 请求中的所有部件进行检查。如果上传的文件大小超过了限制或者文件类型不是允许的类型,则会抛出 `ServletException` 异常,否则将继续处理请求。
阅读全文