/FileUploadTest/src/com/spring/file/bean/User.java
package com.spring.file.bean; import org.springframework.web.multipart.MultipartFile; public class User { private String username; private MultipartFile image; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } }
/FileUploadTest/WebContent/WEB-INF/content/registerForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用戶注冊</title> </head> <body> <h2>用戶注冊</h2> <form action="register" enctype="multipart/form-data" method="post"> <table> <tr> <td>用戶名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>請上傳頭像:</td> <td><input type="file" name="image"></td> </tr> <tr> <td><input type="submit" value="注冊"></td> </tr> </table> </form> </body> </html>
/FileUploadTest/WebContent/WEB-INF/content/userInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件下載</title> </head> <body> <h3>文件下載</h3> <a href="download?filename=${requestScope.user.image.originalFilename}"> ${requestScope.user.image.originalFilename} </a> </body> </html>
/FileUploadTest/src/com/spring/file/controller/FileUploadController.java
package com.spring.file.controller; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; 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 com.spring.file.bean.User; @Controller public class FileUploadController { @RequestMapping(value="/registerform") public String registerForm() { return "registerForm"; } /** * 上傳頭像 * @param request * @param user * @param model * @return * @throws Exception */ @RequestMapping(value="/register") public String register(HttpServletRequest request, @ModelAttribute User user,Model model) throws Exception{ System.out.println(user.getUsername()); //如果文件不為空,寫入上傳路徑 if(!user.getImage().isEmpty()) { //上傳文件路徑 String path = request.getServletContext().getRealPath("/images/"); //上傳文件名 String filename = user.getImage().getOriginalFilename(); File filepath = new File(path,filename); //判斷文件夾是否存在,若不存在就創建 if(!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } //將上傳文件保存到一個目標文件中 user.getImage().transferTo(new File(path+File.separator+filename)); //將用戶添加到model model.addAttribute("user", user); return "userInfo"; }else { return "error"; } } @RequestMapping(value="download") public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,Model model) throws Exception{ //下載文件路徑 String path = request.getServletContext().getRealPath("/images/"); File file = new File(path+File.separator+filename); HttpHeaders headers = new HttpHeaders(); //下載顯示的文件名,解決中文亂碼問題 String downloadFileName = new String(filename.getBytes("UTF-8"),"ISO-8859-1"); //通知瀏覽器以attachment(下載方式)打開圖片 headers.setContentDispositionFormData("attachment", downloadFileName); //application/octet-stream 二進制流數據(最常見的文件下載) headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //201 HttpStatus.CREATED return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED); } }
/FileUploadTest/WebContent/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- 定義Spring MVC的前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 讓Spring MVC的前端控制器攔截所有請求 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
/FileUploadTest/WebContent/WEB-INF/springmvc-config.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- spring可以自動去掃描base-pack下面的包或者子包下面的java文件 如果掃描到由Spring相關注解的類,則把這些類注冊為Spring的bean --> <context:component-scan base-package="com.spring.file.controller"/> <!-- 配置annotation類型的處理映射器 --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> --> <!-- 配置annotation類型的處理器適配器 --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> <!-- 設置配置方案:該配置會自動注冊RequestMappingHandlerMapping和RequestMappingHandlerAdapter --> <mvc:annotation-driven/> <!-- 視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <!-- 前綴 --> <property name="prefix"> <value>/WEB-INF/content/</value> </property> <!-- 后綴 --> <property name="suffix"> <value>.jsp</value> </property> </bean> <!-- 文件上傳配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上傳文件大小限制,上限為10MB,單位為字節 --> <property name="maxUploadSize"> <value>10485760</value> </property> <!-- 請求編碼格式,必須和JSP的pageEncoding屬性一致,以便正確讀取表單內容,默認為ISO-8859-1 --> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean> </beans>
測試結果:以360瀏覽器為例