SpringMVC 通過commons-fileupload實現(xiàn)文件上傳功能
配置
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"/> <!--配置靜態(tài)資源過濾--> <mvc:default-servlet-handler/> <!--配置注解驅(qū)動--> <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"> <!--設(shè)置請求的編碼格式, 必須和pageEncoding的屬性一致, 以便正確讀取表單的值, 默認為ISO-8859-1--> <property name="defaultEncoding" value="utf-8"/> <!--上傳文件的大小限制, 單位為字節(jié) (10485760 = 10M)--> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean> </beans>
文件上傳 Controller
上傳實現(xiàn)一
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 { //上傳路徑保存設(shè)置 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; } }
上傳實現(xiàn)二
這里的文件名稱沒有使用 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 改為數(shù)組即可 @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); // 設(shè)置文件的保存位置 String path = request.getServletContext().getRealPath("/upload"); // 判斷路徑是否存在 File realPath = new File(path); if (!realPath.exists()) { // 如果不存在就創(chuàng)建 realPath.mkdir(); } System.out.println("文件保存路徑 --> " + realPath); // 獲取文件輸入流 InputStream is = file.getInputStream(); // 獲取文件輸出流 FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); // 緩沖區(qū)讀寫文件 byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); os.flush(); } // 關(guān)閉流 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="上傳實現(xiàn)一"> </form> <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload" method="post"> <input type="file" name="file"> <input type="submit" value="上傳實現(xiàn)二"> </form> </body> </html>
依賴
核心依賴就是 commons-fileupload
<!--導(dǎo)入依賴--> <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導(dǎo)入高版本的--> <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>
到此這篇關(guān)于SpringMVC 通過commons-fileupload實現(xiàn)文件上傳的文章就介紹到這了,更多相關(guān)SpringMVC 實現(xiàn)文件上傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot解析JSON數(shù)據(jù)的三種方案
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,易于人閱讀和編寫,同時也易于機器解析和生成,本文給大家介紹了SpringBoot解析JSON數(shù)據(jù)的三種方案,需要的朋友可以參考下2024-03-03"Method?Not?Allowed"405問題分析以及解決方法
項目中在提交表單時,提示“HTTP 405”錯誤——“Method Not Allowed”這里顯示的是,方法不被允許,下面這篇文章主要給大家介紹了關(guān)于"Method?Not?Allowed"405問題分析以及解決方法的相關(guān)資料,需要的朋友可以參考下2022-10-10Java中replace、replaceAll和replaceFirst函數(shù)的用法小結(jié)
相信會java的同學(xué)估計都用過replace、replaceAll、replaceFirst這三個函數(shù),可是,我們真的懂他們嗎?下面通過這篇文章大家再來好好學(xué)習(xí)學(xué)習(xí)下這幾個函數(shù)。2016-09-09Spring MVC打印@RequestBody、@Response日志的方法
這篇文章主要介紹了Spring MVC打印@RequestBody、@Response日志的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02Java中ConcurrentHashMap和Hashtable的區(qū)別
ConcurrentHashMap?和?Hashtable?都是用于在Java中實現(xiàn)線程安全的哈希表數(shù)據(jù)結(jié)構(gòu)的類,但它們有很多區(qū)別,本文就來詳細的介紹一下,感興趣的可以了解一下2023-10-10