目錄
- 配置
- web.xml
- SpringMVC組態檔 applicationContext.xml
- 檔案上傳 Controller
- 上傳實作一
- 上傳實作二
- 測驗
- 依賴
配置
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" >
<!--前綴-->
<property name="prefix" value="https://www.cnblogs.com/WEB-INF/jsp/"/>
<!--后綴-->
<property name="suffix" value="https://www.cnblogs.com/pojo/p/.jsp"/>
</bean>
<!--SpringMVC檔案上傳配置-->
<bean id="multipartResolver" >
<!--設定請求的編碼格式, 必須和pageEncoding的屬性一致, 以便正確讀取表單的值, 默認為ISO-8859-1-->
<property name="defaultEncoding" value="https://www.cnblogs.com/pojo/p/utf-8"/>
<!--上傳檔案的大小限制, 單位為位元組 (10485760 = 10M)-->
<property name="maxUploadSize" value="https://www.cnblogs.com/pojo/p/10485760"/>
<property name="maxInMemorySize" value="https://www.cnblogs.com/pojo/p/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="https://www.cnblogs.com/pojo/p/上傳實作一">
</form>
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload" method="post">
<input type="file" name="file">
<input type="submit" value="https://www.cnblogs.com/pojo/p/上傳實作二">
</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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/255049.html
標籤:Java
上一篇:所以說讀者們才是最優秀的 | 某讀者喜提offer后的分享
下一篇:繼承
