配置
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!--註冊DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVC配置檔案 applicationContext.xml
上傳檔案的核心配置類:CommonsMultipartResolver,注意id="multipartResolver"
不要寫錯
<?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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自動掃描controller包-->
<context:component-scan base-package="com.pro.controller"/>
<!--配置靜態資源過濾-->
<mvc:default-servlet-handler/>
<!--配置註解驅動-->
<mvc:annotation-driven/>
<!--配置檢視解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--字首-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--字尾-->
<property name="suffix" value=".jsp"/>
</bean>
<!--SpringMVC檔案上傳配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--設定請求的編碼格式, 必須和pageEncoding的屬性一致, 以便正確讀取表單的值, 預設為ISO-8859-1-->
<property name="defaultEncoding" value="utf-8"/>
<!--上傳檔案的大小限制, 單位為位元組 (10485760 = 10M)-->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
</beans>
檔案上傳 Controller
上傳實現一
package com.pro.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
@RestController
public class FileController {
/*
* 採用file.transferTo 來儲存上傳的檔案
*/
@RequestMapping("/upload2")
public Map fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上傳路徑儲存設定
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上傳檔案地址
System.out.println("上傳檔案儲存地址 --> "+realPath);
//通過CommonsMultipartFile的方法直接寫檔案(注意這個時候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
Map<Object, Object> hashMap = new HashMap<>();
hashMap.put("code", 0);
hashMap.put("msg", "上傳成功");
return hashMap;
}
}
上傳實現二
這裡的檔名稱沒有使用 UUID組合名稱 為了方便測試
package com.pro.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
@RestController
public class FileController {
// @RequestParam("file") 將 name=file 控制元件得到的檔案封裝成 CommonsMultipartFile 物件
// 批量上傳把 CommonsMultipartFile 改為陣列即可
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
// 獲取檔名稱
String uploadFileName = file.getOriginalFilename();
// 如果檔名為空, 直接返回首頁
if ("".equals(uploadFileName)) {
return "file upload error";
}
System.out.println("上傳檔名 --> " + uploadFileName);
// 設定檔案的儲存位置
String path = request.getServletContext().getRealPath("/upload");
// 判斷路徑是否存在
File realPath = new File(path);
if (!realPath.exists()) {
// 如果不存在就建立
realPath.mkdir();
}
System.out.println("檔案儲存路徑 --> " + realPath);
// 獲取檔案輸入流
InputStream is = file.getInputStream();
// 獲取檔案輸出流
FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
// 緩衝區讀寫檔案
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
os.flush();
}
// 關閉流
os.close();
is.close();
return "file upload success";
}
}
測試
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload2" method="post">
<input type="file" name="file">
<input type="submit" value="上傳實現一">
</form>
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload" method="post">
<input type="file" name="file">
<input type="submit" value="上傳實現二">
</form>
</body>
</html>
依賴
核心依賴就是 commons-fileupload
<!--匯入依賴-->
<dependencies>
<!--單元測試-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--檔案上傳-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api匯入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!--jstl表示式-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>