上傳表單:css
springMVC配置文件中添加 【多部分解析器】html
<!--200*1024*1024即200M resolveLazily屬性啓用是爲了推遲文件解析,以便捕獲文件大小異常 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="209715200" /> <property name="defaultEncoding" value="UTF-8" /> <property name="resolveLazily" value="true" /> </bean>
頁面源碼:java
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib prefix="sf" uri="http://www.springframework.org/tags/form"%> <% 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 'upload.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"> --> <meta charset="utf-8"> <title>圖片上傳</title> </head> <body> <%--文件上傳的話須要enctype="multipart/form-data"--%> <form action="account/uploadPhoto.do" method="post" enctype="multipart/form-data"> <%--這裏設置文件上傳--%> 用戶ID: <input type="text" name="userId"> <br> 文件: <input type="file" name="file"> <input type="submit" value="提交"> </form> </body> </html>
controller:web
/** * 上傳頭像 * @Title:函數 * @Description:Comment for non-overriding methods * @author 張穎輝 * @date 2016-11-23上午11:08:57 * @return */ @ResponseBody @RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST) public Map<String, String> uploadPhoto( @RequestParam("file") MultipartFile mfile, @RequestParam String userId, HttpServletRequest request) { Map<String, String> result = new HashMap<String, String>(); /** 【參數校驗】 **/ if (StringHelper.isNullOrEmpty(userId)) { userId = (String) request.getSession().getAttribute("userid"); if (StringHelper.isNullOrEmpty(userId)) { result.put("success", "false"); result.put("msg", "userId不能爲空"); return result; } } UserVO uvo = this.userService.getUserById(userId); if (uvo == null) { result.put("success", "false"); result.put("msg", "用戶不存在"); return result; } try { if (!mfile.isEmpty()) { /** 【文件上傳】 **/ // 工程內 // String // realPath=request.getSession().getServletContext().getRealPath("/"); // 工程外,訪問須要配置虛擬路徑,配置文件獲取 String realPath = properties.getProperty("storePath"); String cFileName = mfile.getOriginalFilename(); String sFileName = userId + cFileName.substring(cFileName.indexOf(".")); String filePath = realPath + File.separator + sFileName; logger.info(" 【文件上傳】filePath:" + filePath); // String url = realPath+sFileName; File dir = new File(realPath); if (!dir.exists()) { // 判斷指定路徑dir是否存在,不存在則建立路徑 dir.mkdirs(); } File sfile = new File(filePath); // 使用StreamsAPI方式拷貝文件 Streams.copy(mfile.getInputStream(), new FileOutputStream(sfile), true); /** 【關聯用戶】 **/ String headpicPath = properties.getProperty("headPicUrl") + "/" + sFileName; uvo.setHeadpic(headpicPath); //rmi 遠程方法調用,執行數據更新操做。 LoginMSRMI loginMSRMI = (LoginMSRMI) RMIClient.getRMIClient( LoginMSRMI.class, RMIType.LOGINMS_RMI); List<Object> list = loginMSRMI.billiardsMSUpdateUser(uvo); if (Boolean.valueOf(list.get(0).toString())) { result.put("success", "true"); result.put("url", headpicPath); return result; } else { result.put("success", "false"); result.put("msg", "系統錯誤:修改資料異常"); return result; } } else { result.put("success", "false"); result.put("msg", "文件爲空,上傳失敗。"); return result; } } catch (IOException e) { logger.error("文件上傳失敗", e); result.put("success", "false"); result.put("msg", "IO錯誤,上傳失敗"); return result; }finally{ logger.info(" 文件上傳結果:"+result); } }
其中propertis以注入的方式獲取:spring
@Resource(name = "configProperties") private Properties properties;
而且propertis須要在spring配置文件中配置:apache
<util:properties id="configProperties" location="classpath*:application.properties" />
tomcat 須要在server.xml中添加虛擬主機映射<Context>:tomcat
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"> <!-- SingleSignOn valve, share authentication between web applications Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> --> <!-- Access log processes all example. Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/> --> <Context path="/HappyFootBall/upload/headpic" docBase="E:\temp\a"></Context> </Host>
點擊提交:mvc
訪問路徑:app
http://192.168.1.197:8080//HappyFootBall/upload/headpic/009f9f7535594911aee8c944239ea510.jpgwebapp
訪問結果: