<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # Spring Boot 上傳文件 > 原文: [http://zetcode.com/springboot/uploadfile/](http://zetcode.com/springboot/uploadfile/) Spring Boot 上傳文件教程展示了如何使用 Spring Boot 框架上傳單個文件。 Spring 是流行的 Java 應用框架,而 Spring Boot 是 Spring 的演進,可以幫助輕松地創建獨立的,生產級的基于 Spring 的應用。 ## HTML 表單的編碼類型 POST 請求有三種編碼 HTML 表單類型: * `application/x-www-form-urlencoded` * `multipart/form-data` * `text/plain` `application/x-www-form-urlencoded`是默認編碼,其中值編碼在由`&`分隔的鍵值元組中。 `=`字符用于鍵和值之間。 非字母數字字符采用百分比編碼。 此編碼類型不適用于二進制文件。 `multipart/form-data`用于非 acsii 數據和二進制文件。 `input`元素的`type`屬性設置為`file`。 `text/plain`用于調試。 ## Spring 上傳文件示例 在下面的示例中,我們有一個 Web 表單來選擇要上傳到服務器的文件。 該文件被上傳到`/var/www/upload`目錄。 ### 上傳目錄 `/var/www`目錄是 Debian Linux 中 Web 內容的標準目錄。 ```java $ ls -ld /var/www/upload/ drwxrwxr-x 2 www-data www-data 4096 Dec 3 14:29 /var/www/upload/ ``` 我們將文件上傳到`/var/www/upload`目錄。 `www-data`組中的用戶可以修改目錄文件。 因此,運行 Web 服務器的用戶必須在此組中。 ### 應用 以下是 Spring Boot Web 應用的來源。 ```java pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ ├───controller │ │ │ MyController.java │ │ ├───exception │ │ │ StorageException.java │ │ └───service │ │ StorageService.java │ └───resources │ │ application.properties │ └───static │ failure.html │ index.html │ success.html └───test └───java ``` 這是 Spring 應用的項目結構。 `pom.xml` ```java <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>springbootuploadfile</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 這是 Maven `pom.xml`文件。 `com/zetcode/controller/MyController.java` ```java package com.zetcode.controller; import com.zetcode.exception.StorageException; import com.zetcode.service.StorageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class MyController { @Autowired private StorageService storageService; @RequestMapping(value = "/doUpload", method = RequestMethod.POST, consumes = {"multipart/form-data"}) public String upload(@RequestParam MultipartFile file) { storageService.uploadFile(file); return "redirect:/success.html"; } @ExceptionHandler(StorageException.class) public String handleStorageFileNotFound(StorageException e) { return "redirect:/failure.html"; } } ``` `MyController`從請求中讀取文件并將其保存到所選目錄中。 ```java @Autowired private StorageService storageService; ``` `StoreageService`將文件存儲在磁盤上。 ```java @RequestMapping(value = "/doUpload", method = RequestMethod.POST, consumes = {"multipart/form-data"}) public String upload(@RequestParam MultipartFile file) { ``` `upload()`方法映射到`doUpload` URL 模式。 由于我們正在將數據發送到服務器,因此我們使用 POST 請求。 請求參數具有`MultipartFile`類型。 ```java return "redirect:/success.html"; ``` 成功上傳文件后,我們會顯示一條消息。 ```java @ExceptionHandler(StorageException.class) public String handleStorageFileNotFound(StorageException e) { return "redirect:/failure.html"; } ``` 我們有`StorageException`的處理器。 `com/zetcode/StorageException.java` ```java package com.zetcode.exception; public class StorageException extends RuntimeException { public StorageException(String message) { super(message); } public StorageException(String message, Throwable cause) { super(message, cause); } } ``` 這是我們的自定義`StorageException`。 當文件無法存儲在文件系統上時,將引發該錯誤。 `com/zetcode/service/StorageService.java` ```java package com.zetcode.service; import com.zetcode.exception.StorageException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; @Service public class StorageService { @Value("${upload.path}") private String path; public void uploadFile(MultipartFile file) { if (file.isEmpty()) { throw new StorageException("Failed to store empty file"); } try { var fileName = file.getOriginalFilename(); var is = file.getInputStream(); Files.copy(is, Paths.get(path + fileName), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { var msg = String.format("Failed to store file", file.getName()); throw new StorageException(msg, e); } } } ``` `StorageService`從輸入流復制數據并將其保存在磁盤上。 ```java @Value("${upload.path}") private String path; ``` 我們使用`@Value`注解從`application.properties`文件中讀取上傳目錄。 ```java if (file.isEmpty()) { throw new StorageException("Failed to store empty file"); } ``` 我們確保已使用`isEmpty()`方法選擇了一個文件。 ```java var fileName = file.getOriginalFilename(); ``` 我們使用`getOriginalFilename()`方法獲得文件名。 ```java var is = file.getInputStream(); ``` 我們使用`getInputStream()`方法獲得輸入流。 ```java Files.copy(is, Paths.get(path + fileName), StandardCopyOption.REPLACE_EXISTING); ``` 該文件被復制到從與`Files.copy()`輸入流源的目標目錄。 `resources/application.properties` ```java upload.path=/var/www/upload/ ``` 在`application.properties`中,我們有一個`upload.path`屬性,用于指定上傳目錄。 `resources/static/index.html` ```java <!DOCTYPE html> <html> <head> <title>Uploading file</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>Uploading file</h1> <form action="/doUpload" method="post" enctype="multipart/form-data"> <label>Enter file</label> <input type="file" name="file"> <button type="submit">Upload</button> </form> </body> </html> ``` 這是主頁。 它是`src/main/resources/static`目錄中的靜態文件。 它包含一個用于選擇文件并將其發送到 Spring 應用的表單。 ```java <form action="/doUpload" method="post" enctype="multipart/form-data"> ``` 我們選擇了`doUpload` URL 模式。 此表單創建的請求將由 Spring 控制器處理。 `enctype`屬性指定`multipart/form-data`編碼類型,這是使用 HTML 格式上傳文件所必需的。 ```java <input type="file" name="file"> ``` `input`標簽的`type`屬性使用戶可以選擇文件。 ```java <button type="submit">Upload</button> ``` 最后,這是一個提交按鈕。 `resources/static/success.html` ```java <!DOCTYPE html> <html> <head> <title>Success</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p>File successfully uploaded</p> </body> </html> ``` 文件成功上傳到服務器后,將顯示`success.html`。 `resources/static/failure.html` ```java <!DOCTYPE html> <html> <head> <title>Failure</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p>Failed to upload file</p> </body> </html> ``` 文件上傳失敗時,將顯示`failure.html`。 `Application.java` ```java package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 這段代碼設置了 Spring Boot 應用。 在本教程中,我們學習了如何在 Spring 應用中上傳文件。 您可能也對相關教程感興趣: [Spring Boot `@ExceptionHandler`教程](/springboot/exceptionhandler/), [Spring Boot `@PathVariable`教程](/springboot/pathvariable/), [Spring Boot `@RequestParam`教程](/springboot/requestparam/), [Spring Boot REST H2 教程](/articles/springbootresth2/),[獨立的 Spring 應用](/articles/standalonespring/), [Java 教程](/lang/java/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看