SpringBoot實(shí)現(xiàn)文件上傳與下載功能的示例代碼
Spring Boot文件上傳與下載
在實(shí)際的Web應(yīng)用開(kāi)發(fā)中,為了成功上傳文件,必須將表單的method設(shè)置為post,并將enctype設(shè)置為multipart/form-data。只有這種設(shè)置,瀏覽器才能將所選文件的二進(jìn)制數(shù)據(jù)發(fā)送給服務(wù)器。
從Servlet 3.0開(kāi)始,就提供了處理文件上傳的方法,但這種文件上傳需要在Java Servlet中完成,而Spring MVC提供了更簡(jiǎn)單的封裝。Spring MVC是通過(guò)Apache Commons FileUpload技術(shù)實(shí)現(xiàn)一個(gè)MultipartResolver的實(shí)現(xiàn)類CommonsMultipartResolver完成文件上傳的。因此,Spring MVC的文件上傳需要依賴Apache Commons FileUpload組件。
Spring MVC將上傳文件自動(dòng)綁定到MultipartFile對(duì)象中,MultipartFile提供了獲取上傳文件內(nèi)容、文件名等方法,并通過(guò)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):將上傳文件保存到一個(gè)目標(biāo)文件中。
Spring Boot的spring-boot-starter-web已經(jīng)集成了Spring MVC,所以使用Spring Boot實(shí)現(xiàn)文件上傳,更加便捷,只需要引入Apache Commons FileUpload組件依賴即可。
舉例說(shuō)明
下面通過(guò)一個(gè)實(shí)例講解Spring Boot文件上傳與下載的實(shí)現(xiàn)過(guò)程。
【例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)行限制上傳文件大小。
#上傳文件時(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)建選擇文件視圖頁(yè)面
在ch7_2應(yīng)用的src/main/resources/templates目錄下,創(chuàng)建選擇文件視圖頁(yè)面uploadFile.html。該頁(yè)面中有個(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}" /> <!-- 默認(rèn)訪問(wè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="請(qǐng)選擇文件"/> </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個(gè)處理方法,一個(gè)是界面導(dǎo)航方法uploadFile,一個(gè)是實(shí)現(xiàn)文件上傳的upload方法,一個(gè)是顯示將要被下載文件的showDownLoad方法,一個(gè)是實(shí)現(xiàn)下載功能的download方法。核心代碼如下:
@Controller public class TestFileUpload { @RequestMapping("/uploadFile") public String uploadFile() { return "uploadFile"; } /** * 上傳文件自動(dòng)綁定到MultipartFile對(duì)象中, * 在這里使用處理方法的形參接收請(qǐng)求參數(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(); } //將上傳文件保存到一個(gè)目標(biāo)文件中 myfile.transferTo(filePath); } //轉(zhuǎn)發(fā)到一個(gè)請(qǐng)求處理方法,查詢將要下載的文件 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)建將要下載的文件對(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ù)(最常見(jiàn)的文件下載) 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等瀏覽器,則需要說(shuō)明編碼的字符集 * 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)建文件下載視圖頁(yè)面
在ch7_2應(yīng)用的src/main/resources/templates目錄下,創(chuàng)建文件下載視圖頁(yè)面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主類。然后,訪問(wèn)http://localhost:8080/ch7_2/uploadFile測(cè)試文件上傳與下載。
以上就是SpringBoot實(shí)現(xiàn)文件上傳與下載功能的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot文件上傳 下載的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringMvc web.xml配置實(shí)現(xiàn)原理過(guò)程解析
這篇文章主要介紹了SpringMvc web.xml配置實(shí)現(xiàn)原理過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08spring?boot?Slf4j日志框架的體系結(jié)構(gòu)詳解
在項(xiàng)目開(kāi)發(fā)中記錄日志是必做的一件事情,springboot內(nèi)置了slf4j日志框架,下面這篇文章主要給大家介紹了關(guān)于spring?boot?Slf4j日志框架的體系結(jié)構(gòu),需要的朋友可以參考下2022-05-05Java 生成圖片驗(yàn)證碼3種方法(字母、加減乘除、中文)
這篇文章主要介紹了Java 生成圖片驗(yàn)證碼3種方法(字母、加減乘除、中文),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01如何通過(guò)idea實(shí)現(xiàn)springboot集成mybatis
這篇文章主要介紹了如何通過(guò)idea實(shí)現(xiàn)springboot集成mybatis,使用springboot 集成 mybatis后,通過(guò)http請(qǐng)求接口,使得通過(guò)http請(qǐng)求可以直接操作數(shù)據(jù)庫(kù),本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09使用webservice自定義注解處理參數(shù)加解密問(wèn)題
這篇文章主要介紹了使用webservice自定義注解處理參數(shù)加解密問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12