依賴的jar包html
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
實例代碼
uploadForm.jspjava
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文件上傳</title> </head> <body> <h2>文件上傳</h2> <form action="upload" enctype="multipart/form-data" method="post"> <table> <tr> <td>文件描述:</td> <td><input type="text" name="description"></td> </tr> <tr> <td>請選擇文件:</td> <td><input type="file" name="file"></td> </tr> <tr> <td><input type="submit" value="上傳"></td> </tr> </table> </form> </body> </html>
負責上傳文件的表單的編碼類型必須是「Multipart/form-data」
FileUploadController.javaweb
package com.rookie.bigdata.controller; import com.rookie.bigdata.domain.User; 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.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; /** * Created by dell on 2019/6/16. */ @Controller public class FileUploadController { @RequestMapping(value = "/{formName}") public String loginForm(@PathVariable String formName) { //動態條狀頁面 return formName; } // 上傳文件會自動綁定到MultipartFile中 @RequestMapping(value="/upload",method= RequestMethod.POST) public String upload(HttpServletRequest request, @RequestParam("description") String description, @RequestParam("file") MultipartFile file) throws Exception { System.out.println("執行了該方法" + description); //判斷文件是否爲空 if (!file.isEmpty()) { //獲取文件的路徑 String path = request.getServletContext().getRealPath("content"); //獲取上傳文件名 String filename = file.getOriginalFilename(); File filePath = new File(path, filename); //判斷路徑是否存在,不存在就建立一個 if (!filePath.getParentFile().exists()) { filePath.getParentFile().mkdirs(); } file.transferTo(new File(path + File.separator + filename)); return "success"; } else { return "error"; } } @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( "/content/"); // 上傳文件名 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( "/content/"); File file = new File(path+File.separator+ filename); HttpHeaders headers = new HttpHeaders(); // 下載顯示的文件名,解決中文名稱亂碼問題 String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1"); // 通知瀏覽器以attachment(下載方式)打開圖片 headers.setContentDispositionFormData("attachment", downloadFielName); // application/octet-stream : 二進制流數據(最多見的文件下載)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 201 HttpStatus.CREATED return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } }
springmvc會將上傳的文件綁定到MultipartFile對象中,MultipartFile提供了獲取上傳文件內容,文件名等方法,經過transferTo()方法將文件存儲到磁盤中
springmvc-config.xml文件spring
<?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: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"> <context:component-scan base-package="com.rookie.bigdata.controller"/> <!-- 視圖解析器 --> <bean id="viewResolver" 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>
用戶點擊進行文件上傳就能夠了
apache
二、使用對象接受文件
registerForm.jspjson
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; 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>
User.javaapi
public class User implements Serializable { private String username; private MultipartFile image;
輸入用戶名並選擇上傳文件頭像,點擊註冊按鈕上傳用戶頭像進入到下載頁面
瀏覽器
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>文件下載</title> </head> <body> <h3>文件下載</h3> <a href="download?filename=${requestScope.user.image.originalFilename}"> ${requestScope.user.image.originalFilename } </a> </body> </html>
進入到下載頁面點擊下載便可spring-mvc