首先需要导入jar包
创建一个jsp页面
package cn.happy.Controller; import java.io.File; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; @Controller public class MyController { @RequestMapping(value="/first.do") public String doFirst(HttpSession session,MultipartFile uploadfile ) throws Exception{ if (uploadfile.getSize()>0) { //获取前半部分路径 String leftpath=session.getServletContext().getRealPath("/images"); //获取文件名称 String filename = uploadfile.getOriginalFilename(); //限制文件类型 if(filename.endsWith(".jpg")||filename.endsWith(".JPG")){ File file=new File(leftpath,filename); uploadfile.transferTo(file); return "WELCOME.jsp"; } } return "error.jsp"; }
配置文件:
<!-- 配置包扫描器--> <context:component-scan base-package="cn.happy.Controller"></context:component-scan> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> <mvc:annotation-driven/>
原文:http://www.cnblogs.com/Smile-123/p/6269675.html