SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver
一、什么是multipart
The Spittr application calls for file uploads in two places. When a new user registers with the application, you’d like them to be able to provide a picture to associate with their profile. And when a user posts a new Spittle , they may want to upload a photo to go along with their message.The request resulting from a typical form submission is simple and takes the form of multiple name-value pairs separated by ampersands. For example, when submitting the registration form from the Spittr application, the request might look like this:
- firstName=Charles&lastName=Xavier&email=professorx%40xmen.org
- &username=professorx&password=letmein01
Although this encoding scheme is simple and sufficient for typical text-based form submissions, it isn’t robust enough to carry binary data such as an uploaded image. In contrast, multipart form data breaks a form into individual parts, with one part per field. Each part can have its own type. Typical form fields have textual data in their parts, but when something is being uploaded, the part can be binary, as shown in the following multipart request body:
- ------WebKitFormBoundaryqgkaBn8IHJCuNmiW
- Content-Disposition: form-data; name="firstName"
- Charles
- ------WebKitFormBoundaryqgkaBn8IHJCuNmiW
- Content-Disposition: form-data; name="lastName"
- Xavier
- ------WebKitFormBoundaryqgkaBn8IHJCuNmiW
- Content-Disposition: form-data; name="email"
- charles@xmen.com
- ------WebKitFormBoundaryqgkaBn8IHJCuNmiW
- Content-Disposition: form-data; name="username"
- professorx
- ------WebKitFormBoundaryqgkaBn8IHJCuNmiW
- Content-Disposition: form-data; name="password"
- letmein01
- ------WebKitFormBoundaryqgkaBn8IHJCuNmiW
- Content-Disposition: form-data; name="profilePicture"; filename="me.jpg"
- Content-Type: image/jpeg
- [[ Binary image data goes here ]]
- ------WebKitFormBoundaryqgkaBn8IHJCuNmiW--
In this multipart request, the profilePicture part is noticeably different from the other parts. Among other things, it has its own Content-Type header indicating that it’s a JPEG image. And although it may not be obvious, the body of the profile-Picture part is binary data instead of simple text.
二、在Spring中上传文件有多少种方法
DispatcherServlet doesn’t implement any logic for parsing the data in a multipart request. Instead, it delegates to an implementation of Spring’s MultipartResolver strategy interface to resolve the content in a multipart request. Since Spring 3.1,Spring comes with two out-of-the-box implementations of MultipartResolver to choose from:
CommonsMultipartResolver —Resolves multipart requests using Jakarta Commons FileUpload
StandardServletMultipartResolver —Relies on Servlet 3.0 support for multipart requests (since Spring 3.1)
三、配置StandardServletMultipartResolver
1.Java
(1)
- @Bean
- public MultipartResolver multipartResolver() throws IOException {
- return new StandardServletMultipartResolver();
- }
(2)设置上传条件:If you’re configuring DispatcherServlet in a servlet initializer class that implements WebApplicationInitializer , you can configure multipart details by calling setMultipartConfig() on the servlet registration, passing an instance of MultipartConfigElement .
- DispatcherServlet ds = new DispatcherServlet();
- Dynamic registration = context.addServlet("appServlet", ds);
- registration.addMapping("/");
- registration.setMultipartConfig(new MultipartConfigElement("/tmp/spittr/uploads"));
(3)设置上传条件:If you’ve configured DispatcherServlet in a servlet initializer class that extends AbstractAnnotationConfigDispatcherServletInitializer or AbstractDispatcherServletInitializer
- @Override
- protected void customizeRegistration(Dynamic registration) {
- registration.setMultipartConfig(new MultipartConfigElement("/tmp/spittr/uploads"));
- }
(4)设置其他上传条件
The maximum size (in bytes) of any file uploaded. By default there is no limit.
The maximum size (in bytes) of the entire multipart request, regardless of how many parts or how big any of the parts are. By default there is no limit.
The maximum size (in bytes) of a file that can be uploaded without being written to the temporary location. The default is 0, meaning that all uploaded files will be written to disk.
For example, suppose you want to limit files to no more than 2 MB , to limit the entire request to no more than 4 MB , and to write all files to disk. The following use of MultipartConfigElement sets those thresholds:
- @Override
- protected void customizeRegistration(Dynamic registration) {
- registration.setMultipartConfig(new MultipartConfigElement("/tmp/spittr/uploads",2097152, 4194304, 0));
- }
2.在xml中设置上传约束
- <servlet>
- <servlet-name>appServlet</servlet-name>
- <servlet-class>
- org.springframework.web.servlet.DispatcherServlet
- </servlet-class>
- <load-on-startup>1</load-on-startup>
- <multipart-config>
- <location>/tmp/spittr/uploads</location>
- <max-file-size>2097152</max-file-size>
- <max-request-size>4194304</max-request-size>
- </multipart-config>
- </servlet>
四、配置CommonsMultipartResolver
1.Java
(1)
- @Bean
- public MultipartResolver multipartResolver() {
- return new CommonsMultipartResolver();
- }
(2)设置约束
- @Bean
- public MultipartResolver multipartResolver() throws IOException {
- CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
- multipartResolver.setUploadTempDir(new FileSystemResource("/tmp/spittr/uploads"));
- return multipartResolver;
- }
(3)设置约束
- @Bean
- public MultipartResolver multipartResolver() throws IOException {
- CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
- multipartResolver.setUploadTempDir(new FileSystemResource("/tmp/spittr/uploads"));
- multipartResolver.setMaxUploadSize(2097152);
- multipartResolver.setMaxInMemorySize(0);
- return multipartResolver;
- }
Here you’re setting the maximum file size to 2 MB and the maximum in-memory size to 0 bytes. These two properties directly correspond to MultipartConfigElement ’s second and fourth constructor arguments, indicating that no files larger than 2 MB may be uploaded and that all files will be written to disk no matter what size. Unlike MultipartConfigElement , however, there’s no way to specify the maximum multipart request size.
SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver的更多相关文章
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice
No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an e ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener
一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-006- 如何保持重定向的request数据(用model、占位符、RedirectAttributes、model.addFlashAttribute("spitter", spitter);)
一.redirect为什么会丢数据? when a handler method completes, any model data specified in the method is copied ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-004- 处理上传文件
一.用 MultipartFile 1.在html中设置<form enctype="multipart/form-data">及<input type=&quo ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-001- DispatcherServlet的高级配置(ServletRegistration.Dynamic、WebApplicationInitializer)
一. 1.如想在DispatcherServlet在Servlet容器中注册后自定义一些操作,如开启文件上传功能,则可重写通过AbstractAnnotationConfigDispatcherSer ...
- SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍
一. 二.用Java文件配置web application 1. package spittr.config; import org.springframework.web.servlet.suppo ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)
一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error
一. Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra config ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)
一 1.以path parameters的形式给action传参数 @Test public void testSpittle() throws Exception { Spittle expecte ...
随机推荐
- 未能加载文件或程序集“App_global.asax”或它的某一个依赖项
未能加载文件或程序集"App_global.asax"或它的某一个依赖项.生成此程序集的运行时比当前加载的运行时新,无法加载此程序集. 出现这一问题的原因是空间支持framewor ...
- hive外部表自动读取文件夹里的数据
我们在创建表的时候可以指定external关键字创建外部表,外部表对应的文件存储在location指定的目录下,向该目录添加新文件的同时,该表也会读取到该文件(当然文件格式必须跟表定义的一致),删除外 ...
- mybatis 无法转换为内部表示 解决
出现这个问题,一般是JavaBean定义的时候数据类型不准造成的. 其中javabean定义的字段的类型并不需要完全和数据库中的字段一样. 在mapper.xml中可能做了转换 比如 CASE WH ...
- 只有PD号的调起
cicsterm-> CECI -> LI-> P -> TestQuery
- [翻译][MVC 5 + EF 6] 11:实现继承
原文:Implementing Inheritance with the Entity Framework 6 in an ASP.NET MVC 5 Application 1.选择继承映射到数据库 ...
- VS2010 EntityFramework Database First
本文演练介绍如何使用实体框架进行 Database First 开发.通过 Database First,可以从现有数据库对模型进行反向工程处理.模型存储在一个 EDMX 文件(扩展名为 .edmx) ...
- 【HeadFirst设计模式】10.状态模式
定义: 允许对象在内部状态改变时改变它 行为,对象看起来好像修改了它的类. OO原则: 封装变化 多用组合,少用继承 针对接口编程,不针对实现编程 为交互对象之间的松耦合设计而努力 类应该对扩展开放, ...
- apache 工作模式
apache三种工作模式: prefork(2.4前默认)/worker/event(2.4默认)内容整理来自以下网站http://m.blog.csdn.net/article/details?id ...
- SQL 字符替换
--匹配所有字符替换 )),'被替换','替换') --匹配给定位子替换 update 表名 set 列=stuff(列名,从一开始数位数,往后数几位,替换)
- 网站重构-你了解AJAX吗?
AJAX是时下最流行的一种WEB端开发技术,而你真正了解它的一些特性吗?--IT北北报 XMLHTTPRequest(XHR)是目前最常用的技术,它允许异步接收和发送数据,所有的主流浏览器都对它有不错 ...