
- Spring Boot 教程
- Spring Boot - 首頁
- Spring Boot - 簡介
- Spring Boot - 快速入門
- Spring Boot - 引導
- Spring Tool Suite
- Spring Boot - Tomcat 部署
- Spring Boot - 構建系統
- Spring Boot - 程式碼結構
- Spring Bean & 依賴注入
- Spring Boot - 執行器
- Spring Boot - 啟動器
- Spring Boot - 應用程式屬性
- Spring Boot - 配置
- Spring Boot - 註解
- Spring Boot - 日誌記錄
- 構建 RESTful Web 服務
- Spring Boot - 異常處理
- Spring Boot - 攔截器
- Spring Boot - Servlet 過濾器
- Spring Boot - Tomcat 埠號
- Spring Boot - Rest 模板
- Spring Boot - 檔案處理
- Spring Boot - 服務元件
- Spring Boot - Thymeleaf
- 消費 RESTful Web 服務
- Spring Boot - CORS 支援
- Spring Boot - 國際化
- Spring Boot - 排程
- Spring Boot - 啟用 HTTPS
- Spring Boot - Eureka 伺服器
- 使用 Eureka 進行服務註冊
- 閘道器代理伺服器和路由
- Spring Cloud 配置伺服器
- Spring Cloud 配置客戶端
- Spring Boot - 執行器
- Spring Boot - 管理伺服器
- Spring Boot - 管理客戶端
- Spring Boot - 啟用 Swagger2
- Spring Boot - 使用 SpringDoc OpenAPI
- Spring Boot - 建立 Docker 映象
- 跟蹤微服務日誌
- Spring Boot - Flyway 資料庫
- Spring Boot - 傳送電子郵件
- Spring Boot - Hystrix
- Spring Boot - Web Socket
- Spring Boot - 批處理服務
- Spring Boot - Apache Kafka
- Spring Boot - Twilio
- Spring Boot - 單元測試用例
- Rest Controller 單元測試
- Spring Boot - 資料庫處理
- 保護 Web 應用程式
- Spring Boot - OAuth2 與 JWT
- Spring Boot - Google Cloud Platform
- Spring Boot - Google OAuth2 登入
- Spring Boot 資源
- Spring Boot - 快速指南
- Spring Boot - 有用資源
- Spring Boot - 討論
Spring Boot - 檔案處理
在本章中,您將學習如何使用 Web 服務上傳和下載檔案。
檔案上傳
要上傳檔案,您可以使用MultipartFile作為請求引數,並且此 API 應該使用多部分表單資料值。請觀察以下程式碼:
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String fileUpload(@RequestParam("file") MultipartFile file) { return null; }
完整的程式碼如下所示:
FileUploadController.java
package com.tutorialspoint.demo.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadController { @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String fileUpload(@RequestParam("file") MultipartFile file) throws IOException { File convertFile = new File("/var/tmp/"+file.getOriginalFilename()); convertFile.createNewFile(); FileOutputStream fout = new FileOutputStream(convertFile); fout.write(file.getBytes()); fout.close(); return "File is upload successfully"; } }
檔案下載
對於檔案下載,您應該使用 InputStreamResource 來下載檔案。我們需要在響應中設定 HttpHeader Content-Disposition,並需要指定應用程式的響應媒體型別。
注意 - 在以下示例中,檔案應該在應用程式執行的指定路徑上可用。
@GetMapping(value = "/download") public ResponseEntity<Object> downloadFile() throws IOException { String filename = "/var/tmp/logo.png"; File file = new File(filename); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType( MediaType.parseMediaType("application/txt")).body(resource); return responseEntity; }
完整的程式碼如下所示:
FileDownloadController.java
package com.tutorialspoint.demo.controller; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class FileDownloadController { @RequestMapping(value = "/download", method = RequestMethod.GET) public ResponseEntity<Object> downloadFile() throws IOException { String filename = "/var/tmp/logo.png"; File file = new File(filename); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(headers).contentLength( file.length()).contentType(MediaType.parseMediaType("application/txt")).body(resource); return responseEntity; } }
Spring Boot 主應用程式如下所示:
DemoApplication.java
package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
Maven 構建程式碼 - pom.xml 如下所示:
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <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>
Gradle 構建程式碼 - build.gradle 如下所示:
build.gradle
buildscript { ext { springBootVersion = '3.3.3' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 21 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') }
現在您可以建立一個可執行的 JAR 檔案,並使用以下 Maven 或 Gradle 命令執行 Spring Boot 應用程式:
對於 Maven,使用以下命令:
mvn clean install
“BUILD SUCCESS”之後,您可以在 target 目錄下找到 JAR 檔案。
對於 Gradle,您可以使用以下命令:
sgradle clean build
“BUILD SUCCESSFUL”之後,您可以在 build/libs 目錄下找到 JAR 檔案。
現在,使用以下命令執行 JAR 檔案:
java –jar <JARFILE>
這將在 Tomcat 埠 8080 上啟動應用程式,如下所示:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ [32m :: Spring Boot :: [39m [2m (v3.3.3)[0;39m [2024-09-06T11:55:39Z] [org.springframework.boot.StartupInfoLogger] [main] [50] [INFO ] Starting DemoApplication using Java 21.0.3 with PID 4648 (E:\Dev\demo\target\classes started by Tutorialspoint in E:\Dev\demo) [2024-09-06T11:55:39Z] [org.springframework.boot.SpringApplication] [main] [654] [INFO ] No active profile set, falling back to 1 default profile: "default" [2024-09-06T11:55:40Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [111] [INFO ] Tomcat initialized with port 8080 (http) [2024-09-06T11:55:40Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing ProtocolHandler ["http-nio-8080"] [2024-09-06T11:55:40Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting service [Tomcat] [2024-09-06T11:55:40Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting Servlet engine: [Apache Tomcat/10.1.28] [2024-09-06T11:55:40Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing Spring embedded WebApplicationContext [2024-09-06T11:55:40Z] [org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext] [main] [296] [INFO ] Root WebApplicationContext: initialization completed in 1857 ms [2024-09-06T11:55:41Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting ProtocolHandler ["http-nio-8080"] [2024-09-06T11:55:41Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [243] [INFO ] Tomcat started on port 8080 (http) with context path '/' [2024-09-06T11:55:41Z] [org.springframework.boot.StartupInfoLogger] [main] [56] [INFO ] Started DemoApplication in 3.638 seconds (process running for 5.691)
現在在 POSTMAN 應用程式中點選以下 URL,您將看到以下輸出:
檔案下載 - https://:8080/download

檔案上傳 - https://:8080/upload
廣告