SpringMVC文件上传
一.配置web.xml
关键是指定spring-servlet.xml配置文件的位置
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param> <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value> 默认 </init-param> --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
二.spring-servlet.xml配置
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <!-- 设置使用注解的类所在的jar包 --> <context:component-scan base-package="me.mvc,me.base"></context:component-scan> <!-- 完成请求和注解POJO的映射 --> <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> --> <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!--返回字符串格式json--> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 上传文件的关键配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="102400000"></property> </bean> </beans>
三.后台代码(代码中有方法作用的注释)
package me.mvc; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import me.mvc.service.testmvcDao; import net.sf.json.JSONArray; import org.apache.struts2.ServletActionContext; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/mvc/*") public class testmvc { @RequestMapping(value="/uploadindex.do",method=RequestMethod.GET)//上传文件的首页 public String uploadindex() throws Exception{ return "testupload"; } @RequestMapping(value="/upload.do",method=RequestMethod.POST)//上传文件的关键代码 public String upload(HttpServletRequest req) throws Exception{ MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req; MultipartFile file = mreq.getFile("file"); String fileName = file.getOriginalFilename(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String s= req.getSession().getServletContext().getRealPath("upload"); //&&&&&&&&&&&&&&&:D:\apache-tomcat-7.0.27\webapps\SpringMvc\WebRootupload/ System.out.println("&&&&&&&&&&&&&&&:"+s); File targetFile = new File(s, sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'))); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } //model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName); // FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("upload")+ // sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'))); //FileOutputStream out = new FileOutputStream(path+"\\"+fileName+type); //fos.write(file.getBytes()); // fos.flush(); //fos.close(); req.setAttribute("messagex", "上传成功"); return "upload"; } /* @RequestMapping(method=RequestMethod.GET,value="/hello2") public ModelAndView hello2() { ModelAndView view = new ModelAndView("hello2"); return view; }*/ }
四.前端页面
页面有两个部分组成
upload.jsp是上传文件的页面,由于上传文件的页面是跟主页面是配套使用的,所以就有了testupload.jsp这个主页面
1.testupload.jsp的代码,通过ifame嵌套upload.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'gdgl.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <table> <tr> <td>工单管理:</td> <td > <!-- <input id="bk_img" type="hidden" class="easyui-textbox" name="bk_img" /> --> <%-- 嵌套upload.jsp页面 --%> <iframe id="tt" name="tt1" src="<%=path%>/jsp/upload.jsp" frameBorder="0" frameSpacing="0" height="25" width="600" marginHeight="0" marginWidth="0" scrolling="no" ></iframe> </td> </tr> </table> </body> </html>
2.upload.jsp代码
<%=request.getAttribute("messagex")==null?"":request.getAttribute("messagex").toString()%>,返回上传成功后的信息
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% response.setHeader("P3P" , "CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\"" ); String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>文件上传</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" href="<%=path%>/resource/themes/icon.css" type="text/css" /> <link rel="stylesheet" href="<%=path%>/resource/themes/default/easyui.css" type="text/css" /> <script type="text/javascript" src="<%=path%>/resource/js/jquery.min.js"></script> <script type="text/javascript" src="<%=path%>/resource/js/jquery.easyui.min.js"></script> </head> <body> <!-- ${pageContext.request.contextPath}/upload/execute_upload.do --> <!-- ${pageContext.request.contextPath}/upload2/upload2.do --> <table> <td> <form action="<%=path%>/mvc/upload.do" onsubmit="return check()" enctype="multipart/form-data" method="post"> <input type="file" id="curr_sel_image" name="file" style="float: left; width: 170px;" > <input type="submit" style="float: left;padding-left: 0px;" value="上传" /> </form> </td>
<td> <%=request.getAttribute("messagex")==null?"":request.getAttribute("messagex").toString()%> </td> </table> <!-- <br /> <s:fielderror /> --> </body> <script type="text/javascript"> function check(){ var str=document.getElementById("curr_sel_image").value; if(str.length==0) { alert("请选择上传的文件!"); return false; } return true; } </script> </html>
五.页面效果
1.上传前
2.上传后
人多不足以依赖,要生存只有靠自己。
深窥自己的心,而后发觉一切的奇迹在你自己。
凡事皆有终结,因此,耐心是赢得成功的一种手段。