SpringBoot文件上傳與下載功能實(shí)現(xiàn)詳解
前言
文件上傳與下載是Web應(yīng)用開發(fā)中常用的功能之一,在實(shí)際的Web應(yīng)用開發(fā)中,為了成功上傳文件,必須將表單的method設(shè)置為post,并將enctype設(shè)置為multipart/form-data 只有這樣設(shè)置,瀏覽器才能將所選文件的二進(jìn)制數(shù)據(jù)發(fā)送給服務(wù)器
從Servlet3.0開始,就提供了處理文件上傳的方法,但這種文件上傳需要在Java Servlet中完成,而Spring MVC提供了更簡(jiǎn)單的封裝。Spring MVC是通過Apache Commons FileUpload技術(shù)實(shí)現(xiàn)一個(gè)MultipartResolver的實(shí)現(xiàn)類CommonsMultipartResovler完成文件上傳的。因此,Spring MVC的文件上傳需要依賴Apache Commons FileUpload組件
Spring MVC將上傳文件自動(dòng)綁定到MultipartFile對(duì)象中,MultipartFile提供了獲取上傳文件內(nèi)容,文件名等方法。并通過transferTo方法將文件上傳到服務(wù)器的磁盤中,MultipartFile常用方法如下
byte[]getBytes() 獲取文件數(shù)據(jù)
String getContentType() 獲取文件MIME類型
InputStream getInputStream() 獲取表單中文件組件的名字
String getName() 獲取表單中文件組件的名字
String getOriginalFilename() 獲取上傳文件的原名
long getSize() 獲取文件的字節(jié)大小
boolean isEmpty() 是否有選擇上傳文件
void transferTo() 將上傳文件保存到一個(gè)目標(biāo)文件中
Spring Boot的spring-boot-starter-web已經(jīng)集成了Spring MVC 所以使用Spring Boot實(shí)現(xiàn)文件上傳更加敏捷,只需引入Apache Commons FileUpload組件依賴即可
下面通過一個(gè)實(shí)例來加深理解
操作步驟如下
1、引入Apache Commons FileUpload組件依賴
在Web應(yīng)用的ch5_2的pom.xml文件中 添加Apache Commons FileUpload組件依賴 代碼如下
<?xml version="1.0" encoding="UTF-8"?> -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> -<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.ch</groupId> <artifactId>ch5_2</artifactId> <version>0.0.1-SNAPSHOT</version> <name>ch5_2</name> <description>Demo project for Spring Boot</description> -<properties> <java.version>11</java.version> </properties> -<dependencies> -<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <!-- 由于commons-fileupload組件不屬于Spring Boot,所以需要加上版本 --> <version>1.3.3</version> </dependency> -<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> -<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> -<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> -<build> -<plugins> -<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2、設(shè)置上傳文件大小限制
在Web應(yīng)用的ch5_2的配置文件application。properties中 添加如下配置限制上傳文件大小
server.servlet.context-path=/ch5_2
#上傳文件時(shí),默認(rèn)單個(gè)上傳文件大小是1MB,max-file-size設(shè)置單個(gè)上傳文件大小
spring.servlet.multipart.max-file-size=50MB
#默認(rèn)總文件大小是10MB,max-request-size設(shè)置總上傳文件大小
spring.servlet.multipart.max-request-size=500MB
3、創(chuàng)建選擇文件視圖頁面
在ch5_2應(yīng)用的src/main/resources/templates目錄下 創(chuàng)建選擇文件視圖頁面uploadFile.html 該頁面中有一個(gè)enctype屬性值為multipart/form-data的form表單 部分代碼如下
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" rel="external nofollow" />
<!-- 默認(rèn)訪問 src/main/resources/static下的css文件夾-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" rel="external nofollow" />
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">文件上傳示例</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6">
<form class="form-horizontal" action="upload" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="input-group col-md-6">
<span class="input-group-addon">
<i class="glyphicon glyphicon-pencil"></i>
</span>
<input class="form-control" type="text"
name="description" th:placeholder="文件描述"/>
</form>
</div>
</div>
</div>
</body>
</html>4、創(chuàng)建控制器
在ch5_2應(yīng)用的com.ch.ch5_2.controller包中 創(chuàng)建控制器類TestFileUpload 在該類中有4個(gè)處理方法一個(gè)是界面導(dǎo)航方法,uploadfile 一個(gè)是實(shí)現(xiàn)文件上傳的upload方法,一個(gè)是顯示將要被下載文件的showDownLoad 方法,一個(gè)是實(shí)現(xiàn)下載功能的download方法 部分代碼如下
package com.ch.ch5_2.controller;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class TestFileUpload {
/**
* 進(jìn)入文件選擇頁面
*/
@RequestMapping("/uploadFile")
public String uploadFile() {
return "uploadFile";
}
/**
* 上傳文件自動(dòng)綁定到MultipartFile對(duì)象中,
* 在這里使用處理方法的形參接收請(qǐng)求參數(shù)。
* @throws IOException
* @throws IllegalStateException
*/
@RequestMapping("/upload")
public String upload(
HttpServletRequest request,
@RequestParam("description") String description,
@RequestParam("myfile") MultipartFile myfile) throws IllegalStateException, IOException {
System.out.println("文件描述:" + description);
//如果選擇了上傳文件,將文件上傳到指定的目錄uploadFiles
if(!myfile.isEmpty()) {
//上傳文件路徑
String path = request.getServletContext().getRealPath("/uploadFiles/");
//獲得上傳文件原名
String fileName = myfile.getOriginalFilename();
}
/**
* 實(shí)現(xiàn)下載功能
* @throws IOException
*/
@RequestMapping("/download")
public ResponseEntity<byte[]> download(
HttpServletRequest request,
@RequestParam("filename") String filename,
@RequestHeader("User-Agent") String userAgent) throws IOException {
//下載文件路徑
String path = request.getServletContext().getRealPath("/uploadFiles/");
//構(gòu)建將要下載的文件對(duì)象
File downFile = new File(path + File.separator + filename);
//ok表示HTTP中的狀態(tài)是200
BodyBuilder builder = ResponseEntity.ok();
//內(nèi)容長(zhǎng)度
builder.contentLength(downFile.length());
//application/octet-stream:二進(jìn)制流數(shù)據(jù)(最常見的文件下載)
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
//使用URLEncoder.encode對(duì)文件名進(jìn)行編碼
filename = URLEncoder.encode(filename,"UTF-8");
/**
* 設(shè)置實(shí)際的響應(yīng)文件名,告訴瀏覽器文件要用于“下載”和“保存”。
* 不同的瀏覽器,處理方式不同,根據(jù)瀏覽器的實(shí)際情況區(qū)別對(duì)待。
*/
if(userAgent.indexOf("MSIE") > 0) {
//IE瀏覽器,只需要用UTF-8字符集進(jìn)行URL編碼
builder.header("Content-Disposition", "attachment; filename=" + filename);
}else {
/**非IE瀏覽器,如FireFox、Chrome等瀏覽器,則需要說明編碼的字符集
* filename后面有個(gè)*號(hào),在UTF-8后面有兩個(gè)單引號(hào)
*/
builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
}
return builder.body(FileUtils.readFileToByteArray(downFile));
}
}5、創(chuàng)建文件下載視圖頁面
創(chuàng)建視圖頁面showFile.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert t </div> </div> </div> </div> </body> </html>

同樣運(yùn)行Ch52Application主類 然后訪問http://localhost:8080/ch5_2/uploadFile
效果如下

點(diǎn)擊選擇文件后彈出如下彈窗

假如沒有上傳文件 點(diǎn)擊上傳文件以后如下

到此這篇關(guān)于SpringBoot文件上傳與下載功能實(shí)現(xiàn)詳解的文章就介紹到這了,更多相關(guān)SpringBoot文件上傳與下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot文件上傳的原理解析
- SpringBoot+ruoyi框架文件上傳和下載的實(shí)現(xiàn)
- tdesign的文件上傳功能實(shí)現(xiàn)(微信小程序+idea的springboot)
- SpringBoot中的文件上傳和異常處理詳解
- SpringBoot中的文件上傳與下載詳解
- Springboot文件上傳功能的實(shí)現(xiàn)
- SpringBoot文件上傳同時(shí)接收復(fù)雜參數(shù)的過程詳解
- SpringBoot實(shí)現(xiàn)項(xiàng)目文件上傳的方法詳解
- SpringBoot簡(jiǎn)單實(shí)現(xiàn)文件上傳
- SpringBoot整合Hutool實(shí)現(xiàn)文件上傳的使用示例
相關(guān)文章
SpringBoot數(shù)據(jù)庫查詢超時(shí)配置詳解
這篇文章主要介紹了SpringBoot數(shù)據(jù)庫查詢超時(shí)配置,超時(shí)配置可以避免長(zhǎng)時(shí)間占用數(shù)據(jù)庫連接,提高系統(tǒng)的響應(yīng)速度和吞吐量,還可以快速的反饋可以提升用戶體驗(yàn),避免用戶因長(zhǎng)時(shí)間等待而感到挫敗,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-11-11
Java將json對(duì)象轉(zhuǎn)換為map鍵值對(duì)案例詳解
這篇文章主要介紹了Java將json對(duì)象轉(zhuǎn)換為map鍵值對(duì)案例詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09
springsecurity 企業(yè)微信登入的實(shí)現(xiàn)示例
本文主要介紹了springsecurity 企業(yè)微信登入的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
解決jasperreport導(dǎo)出的pdf每頁顯示的記錄太少問題
這篇文章主要介紹了解決jasperreport導(dǎo)出的pdf每頁顯示的記錄太少問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Java編程實(shí)現(xiàn)向文本文件中讀取數(shù)據(jù)之Scanner用法示例
這篇文章主要介紹了Java編程實(shí)現(xiàn)向文本文件中讀取數(shù)據(jù)之Scanner用法,結(jié)合實(shí)例形式分析了java使用Scanner類讀取文本文件相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-03-03
Java結(jié)合Vue項(xiàng)目打包并進(jìn)行服務(wù)器部署
本文主要介紹了Java結(jié)合Vue項(xiàng)目打包并進(jìn)行服務(wù)器部署,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
vue+springboot項(xiàng)目上傳部署tomcat的方法實(shí)現(xiàn)
本文主要介紹了vue+springboot項(xiàng)目上傳部署tomcat的方法實(shí)現(xiàn),包括環(huán)境準(zhǔn)備、配置調(diào)整以及部署步驟,文中通過圖文及示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01

