1 package com.jadyer.controller;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.PrintWriter;
6
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9
10 import org.apache.commons.io.FileUtils;
11 import org.springframework.stereotype.Controller;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 import org.springframework.web.bind.annotation.RequestParam;
14 import org.springframework.web.multipart.MultipartFile;
15
16 /**
17 * SpringMVC中的文件上传
18 * 1)由于SpringMVC使用的是commons-fileupload实现,所以先要将其组件引入项目中
19 * 2)在SpringMVC配置文件中配置MultipartResolver处理器(可在此加入对上传文件的属性限制)
20 * 3)在Controller的方法中添加MultipartFile参数(该参数用于接收表单中file组件的内容)
21 * 4)编写前台表单(注意enctype="multipart/form-data"以及<input type="file" name="****"/>)
22 * PS:由于这里使用了ajaxfileupload.js实现无刷新上传,故本例中未使用表单
23 * ---------------------------------------------------------------------------------------------
24 * 这里用到了如下的jar
25 * commons-io-2.4.jar
26 * commons-fileupload-1.3.jar
27 * commons-logging-1.1.2.jar
28 * spring-aop-3.2.4.RELEASE.jar
29 * spring-beans-3.2.4.RELEASE.jar
30 * spring-context-3.2.4.RELEASE.jar
31 * spring-core-3.2.4.RELEASE.jar
32 * spring-expression-3.2.4.RELEASE.jar
33 * spring-jdbc-3.2.4.RELEASE.jar
34 * spring-oxm-3.2.4.RELEASE.jar
35 * spring-tx-3.2.4.RELEASE.jar
36 * spring-web-3.2.4.RELEASE.jar
37 * spring-webmvc-3.2.4.RELEASE.jar
38 * ---------------------------------------------------------------------------------------------
39 * @create Sep 14, 2013 5:06:09 PM
40 * @author 玄玉<http://blog.csdn.net/jadyer>
41 */
42 @Controller
43 @RequestMapping("/test")
44 public class FileUploadController {
45 /**
46 * 这里这里用的是MultipartFile[] myfiles参数,所以前台就要用<input type="file" name="myfiles"/>
47 * 上传文件完毕后返回给前台[0`filepath],0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
48 */
49 @RequestMapping(value="/fileUpload")
50 public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{
51 //可以在上传文件的同时接收其它参数
52 System.out.println(&