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)文章
java開發(fā)中如何使用JVisualVM進(jìn)行性能分析
JVisualVM是由Sun提供的性能分析工具,如此強(qiáng)大的后盾怎能不強(qiáng)大?在Jdk6.0以后的版本中是自帶的,配置好環(huán)境變量然后在運(yùn)行中輸入“JVisualVm”或直接到Jdk的安裝目錄的Bin目錄下找到運(yùn)行程序即可運(yùn)行。如果是用Jdk1.5或以前版本的朋友就得要單獨(dú)安裝了2015-12-12
SpringBoot接收請(qǐng)求參數(shù)的四種方式總結(jié)
這篇文章主要給大家介紹了關(guān)于SpringBoot接收請(qǐng)求參數(shù)的四種方式,文中通過代碼以及圖文介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用SpringBoot具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09
java網(wǎng)絡(luò)編程基礎(chǔ)知識(shí)介紹
這篇文章主要介紹了java網(wǎng)絡(luò)編程基礎(chǔ)知識(shí)介紹,涉及OSI分層模型和TCP/IP分層模型的對(duì)應(yīng)關(guān)系、IP地址、端口號(hào)、tcp、udp等相關(guān)內(nèi)容,還是比較不錯(cuò)的,這里分享給大家,供需要的朋友參考。2017-11-11
JAVA幫助文檔全系列 JDK1.5 JDK1.6 JDK1.7 官方中英完整版整理
JDK(Java Development Kit,Java開發(fā)包,Java開發(fā)工具)是一個(gè)寫Java的applet和應(yīng)用程序的程序開發(fā)環(huán)境。它由一個(gè)處于操作系統(tǒng)層之上的運(yùn)行環(huán)境還有開發(fā)者編譯,調(diào)試和運(yùn)行用Java語言寫的applet和應(yīng)用程序所需的工具組成2014-01-01
String StringBuilder StringBuffer區(qū)別以及源碼分析
string是C++標(biāo)準(zhǔn)庫的一個(gè)重要的部分,主要用于字符串處理。可以使用輸入輸出流方式直接進(jìn)行string操作,同時(shí),C++的算法庫對(duì)string類也有著很好的支持,并且string類還和c語言的字符串之間有著良好的接口2021-06-06
SpringBoot項(xiàng)目集成Flyway進(jìn)行數(shù)據(jù)庫版本控制的詳細(xì)教程
這篇文章主要介紹了SpringBoot項(xiàng)目集成Flyway進(jìn)行數(shù)據(jù)庫版本控制,本文分步驟通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
java在linux系統(tǒng)下開機(jī)啟動(dòng)無法使用sudo命令的原因及解決辦法
每次開機(jī)自動(dòng)啟動(dòng)的java進(jìn)程,頁面上的關(guān)機(jī)按鈕都無法實(shí)現(xiàn)關(guān)機(jī)功能,但是此時(shí)如果以chb賬號(hào)通過ssh登錄該服務(wù)器,手動(dòng)殺掉tomcat進(jìn)程,然后再重新啟動(dòng)tomcat,頁面上的關(guān)機(jī)按鈕就有效了2013-08-08
Java實(shí)現(xiàn)順時(shí)針輸出螺旋二維數(shù)組的方法示例
這篇文章主要介紹了利用Java如何實(shí)現(xiàn)順時(shí)針輸出螺旋二維數(shù)組的方法示例,文中給出了詳細(xì)的示例代碼和注釋,相信對(duì)大家具有一定的參考價(jià)值,有需要的朋友們下面來一起看看吧。2017-02-02

