#### 1. Create a project
to create a `Maven Project`,` Group Id` as `cn.tedu.spring`,` Artifact Id` select `war` as` SRPINGMVC-03-UPLOAD`, ` Packaging`.
In addition to adding the necessary SpringMVC dependence, also you need to add `commons-fileupload` dependency:
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
#### 2. Static pages
created `index.html` in` webapp` project, the page Requirements:
1. The form `<form>` `method` the property must be` post`, because the uploaded file relative to the average amount of data request parameter, the data is very large, URL does not fit, Further, the value of `genus enctype` values must be` multipart / form-data`:
<form action="" method="post" enctype="multipart/form-data">
2. The form must have controls to navigate the file:
<input type="file" />
The complete code for example:
<form action="" method="post" enctype="multipart/form-data"> <P> Please select the file you want to upload: </ p> <p><input type="file" /></p> <p><input type="submit" value="上传" /></p> </form>
3. receiving an upload request ####
first checks `spring-mvc.xml` regarding component scans the configuration of the root package, and then create` cn.tedu.spring.UploadController` controller class, adding annotation `@ Controller` , then add in the method of processing request controller class:
@RequestMapping("upload.do") public String upload() { return null; }
In the method of processing the request, add `MultipartFile` type parameter, which is uploaded by the client object file package obtained, while processing a request, calling the parameter object` void transferTo (File) `method to save the file :
@Controller public class UploadController { @RequestMapping("upload.do") public String upload( @RequestParam("file") MultipartFile file) throws IllegalStateException, IOException { // 执行保存 File dest = new File("d:/1.jpg"); file.transferTo (); return null; } }
`Action` property value of the static pages of the form must be` upload.do`, `name` property value of the control to browse files must be` file`.
Finally, before use `MultipartFile`, you must also configure` CommonsMultipartResolver` in `spring-mvc.xml` in:
<! - need to use when configuring upload MultipartResolver ->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />