SpringMVC同样使用了apache的文件上传组件。所以需要引入以下包:
apache-commons-fileupload.jar
apache-commons-io.jar
在springAnnotation-servlet.xml中配置
1 23 4 5 6
控制器:
1 package com.cy.springannotation.controller; 2 3 import java.io.File; 4 5 import javax.servlet.http.HttpServletRequest; 6 7 import org.apache.log4j.Logger; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.web.bind.annotation.RequestMapping;10 import org.springframework.web.bind.annotation.RequestMethod;11 import org.springframework.web.bind.annotation.RequestParam;12 import org.springframework.web.multipart.commons.CommonsMultipartFile;13 14 @Controller15 public class FileUploadController {16 private Logger log = Logger.getLogger(this.getClass());17 18 19 /**20 * CommonsMultipartFile file21 * @param file22 * @return23 */24 @RequestMapping(value="/upload.do",method=RequestMethod.POST)25 public String upload(@RequestParam("fileName") CommonsMultipartFile file,HttpServletRequest req){26 //获取原始文件名27 String fileName = file.getOriginalFilename();28 log.info(fileName);29 String path = req.getSession().getServletContext().getRealPath("upload");30 try {31 file.getFileItem().write(new File(path + File.separator + fileName));32 } catch (Exception e) {33 34 log.error(e);35 }36 return "success";37 }38 39 }
上传文件页面:
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 8 9 1036 37 3811 12 文件上传 13 14 15 16 17 18 19 22 23 24 25 26
上传文件就可以了!