您好,登錄后才能下訂單哦!
本篇內容主要講解“SpringMVC如何實現文件上傳下載”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“SpringMVC如何實現文件上傳下載”吧!
pom.xml
<dependencies> <!-- SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.13</version> </dependency> <!-- 日志 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <!-- ServletAPI --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- Spring5和Thymeleaf整合包 --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- springMVC end--> <!-- 導入spring坐標--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.11</version> </dependency> <!-- 導入測試坐標--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- 測試坐標--> <!-- 導入集成測試坐標--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.13</version> </dependency> <!-- 集成測試坐標end--> <!-- 導入mysql坐標--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> <!-- mysql坐標end--> <!-- 導入druid連接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency> <!-- 導入druid連接池end--> <!-- 導入spring上下文--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.11</version> </dependency> <!-- 導入spring上下文end--> <!-- 導入spring web開發api start--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!-- 導入spring web開發end--> <!-- 導入jackson的依賴--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency> <!--上傳功能的關鍵jar --> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> </dependencies>
上傳功能的關鍵jar
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置springMVC的編碼過濾器--> <!-- SpringMVC中處理編碼的過濾器一定要配置到其他過濾器之前,否則無效--> <!-- 字符集過濾器 --> <filter> <description>字符集過濾器</description> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <description>字符集編碼</description> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <!-- 字符集攔截 --> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 注冊前端控制器DispatcherServlet--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
springMVC.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: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"> <!-- 掃描組件--> <context:component-scan base-package="com.vector"/> <!-- 配置Thymeleaf視圖解析器 --> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <!-- 視圖前綴 --> <property name="prefix" value="/WEB-INF/templates/"/> <!-- 視圖后綴 --> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8" /> </bean> </property> </bean> </property> </bean> <!-- 處理響應中文內容亂碼 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="defaultCharset" value="UTF-8" /> <property name="supportedMediaTypes"> <list> <value>text/html</value> <value>application/json</value> </list> </property> </bean> <mvc:view-controller path="/" view-name="index"/> <mvc:view-controller path="/file" view-name="file"/> <mvc:default-servlet-handler/> <mvc:annotation-driven/> <!--必須通過文件解析器的解析才能將文件轉換為MultipartFile對象--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> </beans>
實現頁面跳轉,vue文件解析,上傳內容解析的關鍵
file.html內容demo
<body> <a th:href="@{/testDown}" rel="external nofollow" >下載1.jpg</a> <form th:action="@{/testUp}" method="post" enctype="multipart/form-data"> 頭像: <input type="file" name="photo"><br> <input type="submit" value="上傳"> </form> </body>
package com.vector.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; @Controller public class FileUpAndDownController { @RequestMapping("/testDown") public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException { //獲取ServletContext對象 ServletContext servletContext = session.getServletContext(); //獲取服務器中文件的真實路徑 String realPath = servletContext.getRealPath("/static/img/1.jpg"); //創建輸入流 InputStream is = new FileInputStream(realPath); //創建字節數組 byte[] bytes = new byte[is.available()]; //將流讀到字節數組中 is.read(bytes); //創建HttpHeaders對象設置響應頭信息 MultiValueMap<String, String> headers = new HttpHeaders(); //設置要下載方式以及下載文件的名字 //Content-Disposition 固定回復內容格式 attachment以附件形式下載 filename=1.jpg文件名 //可以將filename拼接為動態命名 headers.add("Content-Disposition", "attachment;filename=1.jpg"); //設置響應狀態碼 HttpStatus statusCode = HttpStatus.OK; //創建ResponseEntity對象 ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode); //關閉輸入流 is.close(); return responseEntity; } @RequestMapping("/testUp") public String testUp(@Value("multipartResolver") MultipartFile photo,HttpSession session) throws IOException { //獲取上傳的文件的文件名 String fileName = photo.getOriginalFilename(); //處理文件重名問題 //重名問題是java.io中寫入同一文件默認覆蓋原文件內容導致圖片被覆蓋. //獲取文件名后綴 String suffixName = fileName.substring(fileName.lastIndexOf(".")); //將UUID作為文件名 uuid是32位隨機數,幾乎不可能會重復 fileName = UUID.randomUUID().toString() + suffixName; //獲取服務器中photo目錄的路徑 ServletContext servletContext = session.getServletContext(); String photoPath = servletContext.getRealPath("photo"); File file = new File(photoPath); //判斷服務器是否存在該路徑 if(!file.exists()){ file.mkdir(); } String finalPath = photoPath + File.separator + fileName; //實現上傳功能 photo.transferTo(new File(finalPath)); return "success"; } }
下載功能測試
上傳功能測試
到此,相信大家對“SpringMVC如何實現文件上傳下載”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。