SpringBoot實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能
引言
在Spring Boot項(xiàng)目中實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能,可以通過使用Spring MVC的MultipartFile接口來處理文件上傳,并使用HttpServletResponse或Resource來實(shí)現(xiàn)文件下載和預(yù)覽。下面是如何實(shí)現(xiàn)這些功能的完整示例。
1. 引入依賴
確保在pom.xml中引入了Spring Boot的相關(guān)依賴。通常情況下,Spring Boot Starter Web已經(jīng)包含了必要的依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2. 創(chuàng)建文件上傳、下載和預(yù)覽的Controller
你可以創(chuàng)建一個(gè)FileController
來處理文件的上傳、下載和預(yù)覽。
import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; @Controller @RequestMapping("/files") public class FileController { // 文件保存路徑(可以通過配置文件進(jìn)行配置) @Value("${file.upload-dir}") private String fileUploadDir; // 文件上傳 @PostMapping("/upload") @ResponseBody public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { // 獲取文件名并且保存文件 String fileName = file.getOriginalFilename(); Path targetLocation = Paths.get(fileUploadDir).resolve(fileName); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); // 返回文件下載的URL String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath() .path("/files/download/") .path(fileName) .toUriString(); return "File uploaded successfully: " + fileDownloadUri; } // 文件下載 @GetMapping("/download/{fileName}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws MalformedURLException { Path filePath = Paths.get(fileUploadDir).resolve(fileName).normalize(); Resource resource = new UrlResource(filePath.toUri()); if (!resource.exists()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } // 文件預(yù)覽(主要針對(duì)圖片、PDF等可以直接在瀏覽器中顯示的文件) @GetMapping("/preview/{fileName}") public ResponseEntity<Resource> previewFile(@PathVariable String fileName) throws MalformedURLException { Path filePath = Paths.get(fileUploadDir).resolve(fileName).normalize(); Resource resource = new UrlResource(filePath.toUri()); if (!resource.exists()) { return ResponseEntity.notFound().build(); } String contentType = "application/octet-stream"; try { contentType = Files.probeContentType(filePath); } catch (IOException e) { e.printStackTrace(); } return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .body(resource); } }
3. 配置文件上傳目錄
在application.properties
或application.yml
中配置文件的上傳路徑:
file.upload-dir=C:/uploads
或者使用application.yml
:
file: upload-dir: C:/uploads
你可以將路徑配置為你項(xiàng)目的目錄,也可以指定到服務(wù)器的某個(gè)位置。
4. 創(chuàng)建上傳目錄
確保在你的系統(tǒng)上已經(jīng)創(chuàng)建了配置文件中指定的上傳目錄,比如C:/uploads
。如果沒有創(chuàng)建,可以通過代碼在項(xiàng)目啟動(dòng)時(shí)自動(dòng)創(chuàng)建:
import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @Component public class FileUploadDirectoryInitializer implements CommandLineRunner { @Value("${file.upload-dir}") private String fileUploadDir; @Override public void run(String... args) throws Exception { Path uploadPath = Paths.get(fileUploadDir); if (!Files.exists(uploadPath)) { Files.createDirectories(uploadPath); } } }
5. 測(cè)試上傳、下載和預(yù)覽
5.1 文件上傳
你可以使用Postman、cURL或者前端頁面來測(cè)試文件上傳功能。上傳文件的URL為:
POST http://localhost:8080/files/upload
參數(shù)名稱為file
。
5.2 文件下載
你可以通過以下URL下載文件:
GET http://localhost:8080/files/download/{fileName}
其中{fileName}
是文件的名稱。
5.3 文件預(yù)覽
你可以通過以下URL預(yù)覽文件(如圖片或PDF):
GET http://localhost:8080/files/preview/{fileName}
6. 處理大文件上傳
對(duì)于大文件上傳,Spring Boot默認(rèn)的最大上傳文件大小可能不滿足需求,可以通過以下配置進(jìn)行調(diào)整:
spring.servlet.multipart.max-file-size=100MB spring.servlet.multipart.max-request-size=100MB
或者在application.yml
中:
spring: servlet: multipart: max-file-size: 100MB max-request-size: 100MB
7. 文件預(yù)覽類型支持
通常情況下,瀏覽器支持預(yù)覽的文件類型包括圖片(如jpeg
、png
)、PDF、文本文件等。如果文件類型不被瀏覽器支持,通常可以通過文件下載的方式處理。
8. 文件刪除功能(可選)
你也可以添加一個(gè)刪除文件的接口,來刪除已上傳的文件:
// 文件刪除 @DeleteMapping("/delete/{fileName}") @ResponseBody public String deleteFile(@PathVariable String fileName) throws IOException { Path filePath = Paths.get(fileUploadDir).resolve(fileName).normalize(); Files.deleteIfExists(filePath); return "File deleted successfully"; }
以上就是SpringBoot實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot文件上傳、下載和預(yù)覽的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java實(shí)現(xiàn)經(jīng)典捕魚達(dá)人游戲的示例代碼
《捕魚達(dá)人》是一款以深海狩獵為題材的休閑競(jìng)技游戲。本文將利用Java實(shí)現(xiàn)這一經(jīng)典的游戲,文中采用了swing技術(shù)進(jìn)行了界面化處理,需要的可以參考一下2022-02-02解決CollectionUtils.isNotEmpty()不存在的問題
這篇文章主要介紹了解決CollectionUtils.isNotEmpty()不存在的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02SpringBoot項(xiàng)目找不到j(luò)avax.servlet.Filter的問題及解決
這篇文章主要介紹了SpringBoot項(xiàng)目找不到j(luò)avax.servlet.Filter的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07Java任意長(zhǎng)度byte數(shù)組轉(zhuǎn)換為int數(shù)組的方法
這篇文章主要給大家介紹了關(guān)于Java任意長(zhǎng)度byte數(shù)組轉(zhuǎn)換為int數(shù)組的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07MyBatis使用標(biāo)簽動(dòng)態(tài)操作數(shù)據(jù)庫詳解
這篇文章主要介紹了MyBatis中使用標(biāo)簽動(dòng)態(tài)操作數(shù)據(jù)庫的方法,動(dòng)態(tài)SQL是指在運(yùn)行PL/SQL塊時(shí)動(dòng)態(tài)輸入SQL語句,是Mybatis的強(qiáng)大特性之?,能夠完成不同條件下不同的sql拼接,需要的朋友可以參考下2024-05-05使用idea生成springboot程序的docker鏡像的操作指南
這篇文章給大家詳細(xì)的介紹了使用idea生成springboot程序的docker鏡像的操作指南,文中通過圖文結(jié)合給大家講解的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2023-12-12Java實(shí)現(xiàn)解析Excel復(fù)雜表頭
這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)解析Excel復(fù)雜表頭功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-01-01