SpringMVC中上传文件还是比较方便的,Spring内置了一些上传文件的支持类,不需要复杂的操作即可上传文件。
文件上传需要两个jar支持,一个是commons-fileupload.jar和commons-io.jar。并且需要在springMVC的配置文件中加入支持文件上传的配置:
12 3
可配置项还有maxuploadsize、uploadTempDir、maxInMemorySize等等。
jsp页面代码:
1 27
文件上传的controller代码:
1 import java.io.File; 2 import java.io.IOException; 3 import javax.servlet.http.HttpServletRequest; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RequestParam; 7 import org.springframework.web.multipart.MultipartFile; 8 9 @Controller10 public class UploadController{11 12 @RequestMapping("/upload")13 public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){14 if(file.isEmpty()){15 System.out.println("file is null---");16 return null;17 }18 19 try {20 String fileName = file.getOriginalFilename();21 fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8"); //防止文件名中的中文乱码,进行utf-8转码22 23 String newPath = request.getSession().getServletContext().getRealPath("upload"); //使用项目下的upload目录存放上传的文件24 String param = request.getParameter("param"); //获取到表单提交的参数25 System.out.println("param:"+param);26 File newFile2 = new File(newPath);27 if(!newFile2.exists()){28 newFile2.mkdir();29 }30 File newFile = new File(newPath+File.separator+fileName);31 file.transferTo(newFile); // 存储文件32 } catch (IOException e) {33 e.printStackTrace();34 }35 return null;36 }37 }