文件上傳是Web開發中的一個重要的功能點。同樣,SpringMVC也可以通過簡單的配置就可以實現文件的上傳以及對上傳的文件的處理。具體步驟如下:
一 新建測試項目以及導入jar包
詳細過程不用多說,項目結構和需要的jar包如下:
二 項目的常規配置以及實現上傳需要的配置
(1)web.xml:
在這里只用了簡單的常規配置,不用多說:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
(2)springmvc-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: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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="cn.zifangsky.* *.controller" /> <context:annotation-config /> <!-- 激活Bean中定義的注解 --> <mvc:annotation-driven /> <!-- 視圖相關配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <!-- 視圖前綴 --> <property name="suffix" value=".jsp" /> <!-- 視圖后綴 --> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="uploadTempDir" value="/tmp" /> <!-- 臨時目錄 --> <property name="maxUploadSize" value="10485760"/> <!-- 10M --> </bean> </beans>
在上面的代碼中的最后一段,配置了一個名為”multipartResolver“的bean,這里就是配置了Commons FileUpload來處理文件上傳
三 文件上傳處理流程
(1)首頁index.jsp:
<% response.sendRedirect("form.html"); %>
(2)模型類User.java:
package cn.zifangsky.model; public class User { private String userName; // 用戶名 private String logoSrc; // 頭像地址 public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getLogoSrc() { return logoSrc; } public void setLogoSrc(String logoSrc) { this.logoSrc = logoSrc; } }
(3)文件上傳表單和結果展示頁fileupload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>Spring MVC文件上傳</title> </head> <body> <h3>圖片文件上傳</h3> <mvc:form modelAttribute="user" action="upload.html" enctype="multipart/form-data"> <table> <tr> <td>用戶名:</td> <td><mvc:input path="userName" /></td> </tr> <tr> <td>選擇頭像:</td> <td><input type="file" name="file" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit" /></td> </tr> </table> </mvc:form> <br><br> <c:if test="${u !=null }"> <h3>上傳結果</h3> <table> <c:if test="${u.userName != null }"> <tr> <td>用戶名:</td> <td>${u.userName}</td> </tr> </c:if> <c:if test="${u.logoSrc != null }"> <tr> <td>頭像:</td> <td><img src="${u.logoSrc}" width="100px" height="100px"></td> </tr> </c:if> </table> </c:if> </body> </html>
可以看出,在上面的form表單中定義的是文件上傳表單,同時為了能夠上傳文件,添加了一個enctype=”multipart/form-data”屬性。后面就是結果展示頁了,使用JSTL標簽來判斷是否有結果,有的話就顯示出來
(4)后臺處理UploadController.java:
package cn.zifangsky.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import cn.zifangsky.model.User; import cn.zifangsky.utils.StringUtile; @Controller public class UploadController { @RequestMapping(value = "/form") public ModelAndView form() { ModelAndView modelAndView = new ModelAndView("fileupload", "user", new User()); return modelAndView; } @RequestMapping(value = "/upload", method = RequestMethod.POST) public ModelAndView upload(User user, @RequestParam("file") MultipartFile tmpFile, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView("fileupload"); if (tmpFile != null) { // 獲取物理路徑 String targetDirectory = request.getSession().getServletContext().getRealPath("/uploads"); String tmpFileName = tmpFile.getOriginalFilename(); // 上傳的文件名 int dot = tmpFileName.lastIndexOf('.'); String ext = ""; //文件后綴名 if ((dot > -1) && (dot < (tmpFileName.length() - 1))) { ext = tmpFileName.substring(dot + 1); } // 其他文件格式不處理 if ("png".equalsIgnoreCase(ext) || "jpg".equalsIgnoreCase(ext) || "gif".equalsIgnoreCase(ext)) { // 重命名上傳的文件名 String targetFileName = StringUtile.renameFileName(tmpFileName); // 保存的新文件 File target = new File(targetDirectory, targetFileName); try { // 保存文件 FileUtils.copyInputStreamToFile(tmpFile.getInputStream(), target); } catch (IOException e) { e.printStackTrace(); } User u = new User(); u.setUserName(user.getUserName()); u.setLogoSrc(request.getContextPath() + "/uploads/" + targetFileName); modelAndView.addObject("u", u); } return modelAndView; } return modelAndView; } }
在上面的upload方法中,為了接收上傳的文件,因此使用了一個MultipartFile類型的變量來接收上傳的臨時文件,同時為了給文件進行重命名,我調用了一個renameFileName方法,這個方法的具體內容如下:
/** * 文件重命名 */ public static String renameFileName(String fileName) { String formatDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date()); // 當前時間字符串 int random = new Random().nextInt(10000); String extension = fileName.substring(fileName.lastIndexOf(".")); // 文件后綴 return formatDate + random + extension; }
至此,全部處理邏輯已經完成。
四 效果測試
(1)文件上傳表單:
(2)上傳結果:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。