SpringMVC中文件的上傳與下載詳細(xì)解析
一、搭建初始環(huán)境
1.創(chuàng)建一個(gè)普通的 springboot 項(xiàng)目。
2.導(dǎo)入相關(guān)依賴
<dependencies> <!--操作文件的一些工具類--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--springweb--> <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> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
二、文件的上傳
2.1 編寫前端頁(yè)面
在 resource/static 路徑下創(chuàng)建 file.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/file/upload" method="post" enctype="multipart/form-data"> <input name="image" type="file"/><br> <input type="submit" value="submit"> </form> </body> </html>
提交文件時(shí),form 表單的 enctype 屬性值必須為 multipart/form-data,例如 enctype="multipart/form-data"
2.2 編寫后端接口
2.2.1 編寫配置文件
file: # 存放文件的地址 path: "G:/springboot/springcloud/ems_parent/ems-empl/src/main/resources/static/"
2.2.2 編寫 Controller 接口類
@RestController public class FIleController { @Value(value = "${file.path}") private String realPath; @PostMapping(value = "/file/upload") public void upload(@RequestPart MultipartFile image,HttpServletRequest request) throws IOException { System.out.println("文件的原始名:" + image.getOriginalFilename()); System.out.println("文件的大小:" + image.getSize()); System.out.println("文件的類型:" + image.getContentType()); // 1.通過(guò) commons-fileupload 提供的工具類獲取原始文件的文件類型后綴。 String extension = FilenameUtils.getExtension(image.getOriginalFilename()); // 2.拼接新的文件名 String fileNewName = UUID.randomUUID().toString().replace("-","") + "." + extension; //3.將文件分日期存放 LocalDate now = LocalDate.now(); // 獲取當(dāng)前日期 File file = new File(realPath, now.toString()); //如果文件不存在創(chuàng)建當(dāng)前目錄 if (!file.exists()) file.mkdir(); // 4.MultipartFile 提供的方法可以直接將 MultipartFile 類型的文件存儲(chǔ)指定的路徑 image.transferTo(new File(file,fileNewName)); } }
commons-fileupload 提供的工具類:
- FilenameUtils.getExtension():可以根據(jù)傳入的文件名參數(shù)獲取文件的后綴。(a.txt --> txt)
- IOUtils.copy(inputStream,outputStream):自動(dòng)將輸入流讀入輸出流
JDK8 提供的新的日期類:
- LocalTime.now():獲取當(dāng)前時(shí)間。(例如:16:52:07.686)
- LocalDate.now():獲取日期。(例如:2021-04-27)
- LocalDateTime.now():獲取當(dāng)前時(shí)間和日期。(例如:2021-04-27T16:52:07.686)
三、文件的下載
3.1 編寫前端頁(yè)面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/file/download?fileName=504dd76bce544057963e335bc8dff449.jpg" rel="external nofollow" >文件下載</a> </body> </html>
3.2 編寫后端接口
@RestController public class FIleController { @RequestMapping(value = "/file/download") public void upload1(String fileName, HttpServletResponse response) throws IOException { // 獲取文件輸入流 FileInputStream inputStream = new FileInputStream(new File(realPath,fileName)); ServletOutputStream outputStream = response.getOutputStream(); System.out.println(realPath+fileName); //設(shè)置響應(yīng)頭和文件類型 attachment為附件形式下載 inline為在線打開(kāi) response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8")); response.setContentType("text/plain;charset=UTF-8"); // 將輸入流讀入輸出流 IOUtils.copy(inputStream,outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); // int len; // byte[] bytes = new byte[1024]; // while (true){ // len = inputStream.read(bytes); // if (len == -1) break; // outputStream.write(bytes); // } // // inputStream.close(); // outputStream.close(); } }
- 文件在線打開(kāi)不下載問(wèn)題:需要設(shè)置響應(yīng)頭 content-disposition: attachment;fileName=文件名(attachment為附件形式下載 inline為在線打開(kāi))
- 下載的文件名和文件亂碼問(wèn)題:
- 文件亂碼:需要設(shè)置 響應(yīng)頭 Content-Type: text/plain;charset=UTF-8
- 文件名亂碼:需要對(duì)文件名進(jìn)行URLEncoder.encode(fileName,"UTF-8")編碼
四、springCloud 中的文件上傳
通過(guò) openFeign 調(diào)用文件上傳接口。
4.1 導(dǎo)入 openFeign 的依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
4.2 在啟動(dòng)類上添加注解
在啟動(dòng)類上添加 @EnableFeignClients 注解,開(kāi)啟 openFeign 服務(wù)。
@SpringBootApplication @EnableFeignClients public class EmsUsersApplication { public static void main(String[] args) { SpringApplication.run(EmsUsersApplication.class, args); } }
4.3 編寫 openFeignClient
@FeignClient("files") public interface FileClient { @PostMapping(value = "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) void upload(@RequestPart MultipartFile image); }
上傳文件時(shí):
- 必須指定 consumes = MediaType.MULTIPART_FORM_DATA_VALUE
- 必須在 MultipartFile 類型的參數(shù)前添加 @RequestPart 注解
到此這篇關(guān)于SpringMVC中文件的上傳與下載詳細(xì)解析的文章就介紹到這了,更多相關(guān)SpringMVC文件的上傳與下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java基礎(chǔ)教程之基本類型數(shù)據(jù)類型、包裝類及自動(dòng)拆裝箱
這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)教程之基本類型數(shù)據(jù)類型、包裝類及自動(dòng)拆裝箱的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06SpringData JPA快速上手之關(guān)聯(lián)查詢及JPQL語(yǔ)句書寫詳解
JPA都有SpringBoot的官方直接提供的starter,而Mybatis沒(méi)有,直到SpringBoot 3才開(kāi)始加入到官方模版中,這篇文章主要介紹了SpringData JPA快速上手,關(guān)聯(lián)查詢,JPQL語(yǔ)句書寫的相關(guān)知識(shí),感興趣的朋友一起看看吧2023-09-09SpringBoot+mybatis+Vue實(shí)現(xiàn)前后端分離項(xiàng)目的示例
本文主要介紹了SpringBoot+mybatis+Vue實(shí)現(xiàn)前后端分離項(xiàng)目的示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12SpringBoot快速實(shí)現(xiàn)接口消息加密的過(guò)程詳解
在項(xiàng)目中,為了保證數(shù)據(jù)的安全,我們常常會(huì)對(duì)傳遞的數(shù)據(jù)進(jìn)行加密,常用的加密算法包括對(duì)稱加密(AES)和非對(duì)稱加密(RSA),博主選取碼云上最簡(jiǎn)單的API加密項(xiàng)目進(jìn)行下面的講解,需要的朋友可以參考下2023-11-11elasticsearch開(kāi)發(fā)中data-streams使用解析
這篇文章主要為大家介紹了elasticsearch開(kāi)發(fā)中data-streams使用解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08Java獲取當(dāng)前時(shí)間的時(shí)間戳方法總結(jié)
Java中獲取時(shí)間戳的方式有很多種,下面這篇文章主要給大家介紹了關(guān)于Java獲取當(dāng)前時(shí)間的時(shí)間戳的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用java具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-06-06spring boot @PathVariable傳遞帶反斜杠參數(shù) / 的處理
這篇文章主要介紹了spring boot @PathVariable傳遞帶反斜杠參數(shù) / 的處理操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02使用Java 8中的Lambda表達(dá)式實(shí)現(xiàn)工廠模式
這篇文章主要給大家介紹了使用Java 8中的Lambda表達(dá)式實(shí)現(xiàn)工廠模式的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-04-04