Trong ứng dụng web, người dùng thường gửi hai loại dữ liệu: thông tin dạng văn bản và tập tin (hình ảnh, tài liệu, video...). Bài viết này tập trung vào việc cấu hình xử lý yêu cầu multipart (đa phần) trong Spring MVC, đây là bước thiết lập cơ bản duy nhất cần thực hiện. Phần còn lại bao gồm tạo form tải lên và viết phương thức xử lý trong controller.
1. Cấu hình bộ phân tích multipart bằng JavaConfig
Spring cung cấp giao diện MultipartResolver để xử lý yêu cầu multipart. Từ phiên bản Servlet 3.0 và Spring 3.1, StandardServletMultipartResolver là lựa chọn tối ưu. Dưới đây là cách khai báo bean trong ứng dụng Spring:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
@Bean
public MultipartResolver fileUploadConfig() {
return new StandardServletMultipartResolver();
}
}
2. Tùy chỉnh DispatcherServlet để quản lý giới hạn tải lên
Có thể thiết lập các thông số cho StandardServletMultipartResolver thông qua DispatcherServlet:
- Đường dẫn lưu tập tin tạm thời
- Giới hạn kích thước tập tin (byte)
- Giới hạn kích thước yêu cầu toàn bộ (byte)
- Điều kiện lưu tập tin vào ổ đĩa (kích thước tối thiểu)
Ví dụ cấu hình:
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
// Cấu hình thư mục lưu tạm và giới hạn
registration.setMultipartConfig(new MultipartConfigElement(
"/var/tmp/app-uploads",
2097152L, // Giới hạn tập tin: 2MB
4194304L, // Giới hạn yêu cầu: 4MB
0 // Lưu tất cả tập tin vào đĩa
));
}
}
Lưu ý: Thư mục /var/tmp/app-uploads phải tồn tại trước khi khởi động ứng dụng, nếu không sẽ xảy ra lỗi:
The temporary upload location [path] is not valid
Hệ thống sẽ tự tạo thư mục nếu được cấu hình đúng, nhưng cần đảm bảo quyền truy cập cho thư mục này.