Spring MVC 为文件上传提供了直接的支持,这种支持是通过即插即用的 MultipartResolver 实现的,MultipartResolver 是SpringMVC九大组件之一。Spring 用 Jakarta Commons FileUpload 技术实现了一个MultipartResolver实现类:CommonsMultipartResovler
二.配置
Spring MVC 上下文中默认没有装配 MultipartResovler,因此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 MultipartResolver,并且配置的bean的id必须是multipartResolver,因为这个组件在初始化时是按照id去IOC容器中查找的。九大组件有些是按id查找,有些是按class查找。
/** * Max file size. Values can use the suffixes "MB" or "KB" to indicate megabytes or * kilobytes, respectively. */ privateStringmaxFileSize="1MB";
/** * Max request size. Values can use the suffixes "MB" or "KB" to indicate megabytes or * kilobytes, respectively. */ privateStringmaxRequestSize="10MB";
/** * Threshold after which files are written to disk. Values can use the suffixes "MB" * or "KB" to indicate megabytes or kilobytes, respectively. */ privateStringfileSizeThreshold="0";
/** * Whether to resolve the multipart request lazily at the time of file or parameter * access. */ privatebooleanresolveLazily=false;
//省略......
如果超过1MB,会抛出如下异常。
1
Spring Boot:The field file exceeds its maximum permitted size of 1048576 bytes.