SpringBoot實(shí)現(xiàn)文件上傳與下載功能的示例代碼
Spring Boot文件上傳與下載
在實(shí)際的Web應(yīng)用開發(fā)中,為了成功上傳文件,必須將表單的method設(shè)置為post,并將enctype設(shè)置為multipart/form-data。只有這種設(shè)置,瀏覽器才能將所選文件的二進(jìn)制數(shù)據(jù)發(fā)送給服務(wù)器。
從Servlet 3.0開始,就提供了處理文件上傳的方法,但這種文件上傳需要在Java Servlet中完成,而Spring MVC提供了更簡單的封裝。Spring MVC是通過Apache Commons FileUpload技術(shù)實(shí)現(xiàn)一個MultipartResolver的實(shí)現(xiàn)類CommonsMultipartResolver完成文件上傳的。因此,Spring MVC的文件上傳需要依賴Apache Commons FileUpload組件。
Spring MVC將上傳文件自動綁定到MultipartFile對象中,MultipartFile提供了獲取上傳文件內(nèi)容、文件名等方法,并通過transferTo方法將文件上傳到服務(wù)器的磁盤中,MultipartFile的常用方法如下:
- byte[] getBytes():獲取文件數(shù)據(jù)。
- String getContentType():獲取文件MIME類型,如image/jpeg等。
- InputStream getInputStream():獲取文件流。
- String getName():獲取表單中文件組件的名字。
- String getOriginalFilename():獲取上傳文件的原名。
- long getSize():獲取文件的字節(jié)大小,單位為byte。
- boolean isEmpty():是否有(選擇)上傳文件。
- void transferTo(File dest):將上傳文件保存到一個目標(biāo)文件中。
Spring Boot的spring-boot-starter-web已經(jīng)集成了Spring MVC,所以使用Spring Boot實(shí)現(xiàn)文件上傳,更加便捷,只需要引入Apache Commons FileUpload組件依賴即可。
舉例說明
下面通過一個實(shí)例講解Spring Boot文件上傳與下載的實(shí)現(xiàn)過程。
【例7】Spring Boot文件上傳與下載。
具體實(shí)現(xiàn)步驟如下。
1.引入Apache Commons FileUpload組件依賴
在Web應(yīng)用ch7_2的pom.xml文件中,添加Apache Commons FileUpload組件依賴,具體代碼如下:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<!-- 由于commons-fileupload組件不屬于Spring Boot,所以需要加上版本 -->
<version>1.4</version>
</dependency>
2.設(shè)置上傳文件大小限制
在Web應(yīng)用ch7_2的配置文件application.properties中,添加如下配置進(jìn)行限制上傳文件大小。
#上傳文件時,默認(rèn)單個上傳文件大小是1MB,max-file-size設(shè)置單個上傳文件大小 spring.servlet.multipart.max-file-size=50MB #默認(rèn)總文件大小是10MB,max-request-size設(shè)置總上傳文件大小 spring.servlet.multipart.max-request-size=500MB
3.創(chuàng)建選擇文件視圖頁面
在ch7_2應(yīng)用的src/main/resources/templates目錄下,創(chuàng)建選擇文件視圖頁面uploadFile.html。該頁面中有個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}" />
<!-- 默認(rèn)訪問 src/main/resources/static下的css文件夾-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
</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="文件描述"/>
</div>
</div>
<div class="form-group">
<div class="input-group col-md-6">
<span class="input-group-addon">
<i class="glyphicon glyphicon-search"></i>
</span>
<input class="form-control" type="file"
name="myfile" th:placeholder="請選擇文件"/>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<div class="btn-group btn-group-justified">
<div class="btn-group">
<button type="submit" class="btn btn-success">
<span class="glyphicon glyphicon-share"></span>
上傳文件
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>4.創(chuàng)建控制器
在ch7_2應(yīng)用的com.ch.ch7_2.controller包中,創(chuàng)建控制器類TestFileUpload。在該類中有4個處理方法,一個是界面導(dǎo)航方法uploadFile,一個是實(shí)現(xiàn)文件上傳的upload方法,一個是顯示將要被下載文件的showDownLoad方法,一個是實(shí)現(xiàn)下載功能的download方法。核心代碼如下:
@Controller
public class TestFileUpload {
@RequestMapping("/uploadFile")
public String uploadFile() {
return "uploadFile";
}
/**
* 上傳文件自動綁定到MultipartFile對象中,
* 在這里使用處理方法的形參接收請求參數(shù)。
*/
@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();
File filePath = new File(path + File.separator + fileName);
//如果文件目錄不存在,創(chuàng)建目錄
if(!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
//將上傳文件保存到一個目標(biāo)文件中
myfile.transferTo(filePath);
}
//轉(zhuǎn)發(fā)到一個請求處理方法,查詢將要下載的文件
return "forward:/showDownLoad";
}
/**
* 顯示要下載的文件
*/
@RequestMapping("/showDownLoad")
public String showDownLoad(HttpServletRequest request, Model model) {
String path = request.getServletContext().getRealPath("/uploadFiles/");
File fileDir = new File(path);
//從指定目錄獲得文件列表
File filesList[] = fileDir.listFiles();
model.addAttribute("filesList", filesList);
return "showFile";
}
/**
* 實(shí)現(xiàn)下載功能
*/
@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)建將要下載的文件對象
File downFile = new File(path + File.separator + filename);
//ok表示HTTP中的狀態(tài)是200
BodyBuilder builder = ResponseEntity.ok();
//內(nèi)容長度
builder.contentLength(downFile.length());
//application/octet-stream:二進(jìn)制流數(shù)據(jù)(最常見的文件下載)
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
//使用URLEncoder.encode對文件名進(jìn)行編碼
filename = URLEncoder.encode(filename,"UTF-8");
/**
* 設(shè)置實(shí)際的響應(yīng)文件名,告訴瀏覽器文件要用于“下載”和“保存”。
* 不同的瀏覽器,處理方式不同,根據(jù)瀏覽器的實(shí)際情況區(qū)別對待。
*/
if(userAgent.indexOf("MSIE") > 0) {
//IE瀏覽器,只需要用UTF-8字符集進(jìn)行URL編碼
builder.header("Content-Disposition", "attachment; filename=" + filename);
}else {
/**非IE瀏覽器,如FireFox、Chrome等瀏覽器,則需要說明編碼的字符集
* filename后面有個*號,在UTF-8后面有兩個單引號
*/
builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
}
return builder.body(FileUtils.readFileToByteArray(downFile));
}
}5.創(chuàng)建文件下載視圖頁面
在ch7_2應(yīng)用的src/main/resources/templates目錄下,創(chuàng)建文件下載視圖頁面showFile.html。核心代碼如下:
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">文件下載示例</h3>
</div>
</div>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">文件列表</h3>
</div>
<div class="panel-body">
<div class="table table-responsive">
<table class="table table-bordered table-hover">
<tbody class="text-center">
<tr th:each="file,fileStat:${filesList}">
<td>
<span th:text="${fileStat.count}"></span>
</td>
<td>
<!--file.name相當(dāng)于調(diào)用getName()方法獲得文件名稱 -->
<a th:href="@{download(filename=${file.name})}">
<span th:text="${file.name}"></span>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>6.運(yùn)行
首先,運(yùn)行Ch72Application主類。然后,訪問http://localhost:8080/ch7_2/uploadFile測試文件上傳與下載。
以上就是SpringBoot實(shí)現(xiàn)文件上傳與下載功能的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot文件上傳 下載的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringCloud微服務(wù)的調(diào)用與遠(yuǎn)程調(diào)用測試示例
這篇文章主要介紹了SpringCloud微服務(wù)的調(diào)用與遠(yuǎn)程調(diào)用測試示例,服務(wù)調(diào)用者-可以暫時認(rèn)為是與用戶交互的角色(因?yàn)榇嬖谖⒎?wù)之間的調(diào)用),可以根據(jù)該用戶的類型將其賦予不同的服務(wù)調(diào)用權(quán)限,通過一次http請求訪問調(diào)用對應(yīng)的微服務(wù)獲取想要的數(shù)據(jù)2023-04-04
Java使用JDBC或MyBatis框架向Oracle中插入XMLType數(shù)據(jù)
XMLType是Oracle支持的一種基于XML格式存儲的數(shù)據(jù)類型,這里我們共同來探究Java使用JDBC或MyBatis框架向Oracle中插入XMLType數(shù)據(jù)的方法:2016-07-07
java文件/圖片的上傳與下載以及MultipartFile詳解
文章介紹了MultipartFile類的使用,包括獲取文件名、文件類型、文件大小等方法,以及如何處理多文件上傳和文件大小限制,同時提供了文件上傳和下載的示例代碼2025-02-02
解決引用slf4j中Logger.info只打印出文字沒有數(shù)據(jù)的問題
這篇文章主要介紹了解決引用slf4j中Logger.info只打印出文字沒有數(shù)據(jù)的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

