SpringMVC upload files are processed through MultipartResolver (Multipart parser), which is an interface for MultipartResolver, which has two implementation classes
CommonsMultipartResolver | Relying on the Jakarta Common FileUplode project under Apache to parse Multipart requests, it can be used in various versions of spring, but it can only be achieved by relying on third-party implementation packages |
StandardServletMultipartResolver | It is the product after spring 3.1, it depends on the implementation of Servlet 3.0 or higher, it does not need to depend on third-party packages |
You can use CommonsMultipartResolver to upload files, or you can use StandardServletMultipartResolver to upload files. Let's take CommonsMultipartResolver as an example to upload files to see how to write them.
Using CommonsMultipartResolver |
1. When using CommonsMultipartResolver, you need to depend on two packages, you can add the dependencies of these two packages in pom.xml | Apache's commons-io and commons-fileupload |
2. Configure the CommonsMultipartResolver bean in the applicationContext.xml file | <!-- To use CommonsMultipartResolver it needs to import two dependencies--> <property name="maxUploadSize"> <!-- The maximum number of bytes to read a file into memory, usually 1024 --> |
Now we can write the controller to receive the file submission request from the foreground
front desk:
Front page | <form method="post" action="./uploadPart" enctype="multipart/form-data"><!-- The submission encoding type of the uploaded file should be multipart/form-data--> |
Background (there are two ways to handle file upload requests):
The first: HttpServletRequest |
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) // 判断保存路径是否存在,不存在则创建 mkdirs表示创建多层目录 mkdir只能创建一层 |
第二种:MultipartFile |
@RequestMapping(value = "/uplodeFileMultipartFile", method = RequestMethod.POST) |