亚洲一区精品自拍_2021年国内精品久久_男同十八禁gv在线观看_免费观看a级性爱黄片

Article / 文章中心

Spring認證指南:了解如何構(gòu)建一個多文件上傳的 Spring 應(yīng)用程序

發(fā)布時間:2022-02-08 點擊數(shù):937


image

本攻略將引導(dǎo)您完結(jié)創(chuàng)立能夠接納 HTTP 多部分文件上傳的服務(wù)器應(yīng)用程序的進程。

你將制作什么

您將創(chuàng)立一個承受文件上傳的 Spring Boot Web 應(yīng)用程序。您還將構(gòu)建一個簡單的 HTML 界面來上傳測驗文件。

你需求什么

  • 約15分鐘
  • 最喜歡的文本編輯器或 IDE
  • JDK 1.8或更高版本
  • Gradle 4+或Maven 3.2+
  • 您還能夠?qū)⒋a直接導(dǎo)入 IDE:彈簧工具套件 (STS)IntelliJ IDEA

怎么完結(jié)本攻略

像大多數(shù) Spring入門攻略一樣,您能夠從頭開端并完結(jié)每個進程,也能夠繞過您現(xiàn)已了解的基本設(shè)置進程。不管哪種辦法,您終究都會得到作業(yè)代碼。

從頭開端,請持續(xù)從 Spring Initializr 開端。

越過基礎(chǔ)知識,請履行以下操作:

完結(jié)后,您能夠?qū)φ罩械拇a檢查成果
gs-uploading-files/complete。

從 Spring Initializr 開端

您能夠運用這個預(yù)先初始化的項目并單擊 Generate 下載 ZIP 文件。此項目裝備為適合本教程中的示例。

手動初始化項目:

  1. 導(dǎo)航到https://start.spring.io。該服務(wù)提取應(yīng)用程序所需的一切依靠項,并為您完結(jié)大部分設(shè)置。
  2. 挑選 Gradle 或 Maven 以及您要運用的言語。本攻略假定您挑選了 Java。
  3. 單擊Dependencies并挑選Spring WebThymeleaf。
  4. 單擊生成。
  5. 下載生成的 ZIP 文件,該文件是依據(jù)您的挑選裝備的 Web 應(yīng)用程序的存檔。

假如您的 IDE 具有 Spring Initializr 集成,您能夠從您的 IDE 完結(jié)此進程。

你也能夠從 Github 上 fork 項目并在你的 IDE 或其他編輯器中翻開它。

創(chuàng)立應(yīng)用程序類

要發(fā)動 Spring Boot MVC 應(yīng)用程序,首要需求一個發(fā)動器。在此示例中,
spring-boot-starter-thymeleaf并且spring-boot-starter-web已作為依靠項增加。要運用 Servlet 容器上傳文件,您需求注冊一個MultipartConfigElement類(在 web.xml 中)。感謝 Spring Boot,一切都是為您主動裝備的!

開端運用此應(yīng)用程序所需的只是以下UploadingFilesApplication類(來自
src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java):

package com.example.uploadingfiles; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class UploadingFilesApplication {  public static void main(String[] args) {  SpringApplication.run(UploadingFilesApplication.class, args);  } }

作為主動裝備 Spring MVC 的一部分,Spring Boot 將創(chuàng)立一個MultipartConfigElementbean 并為文件上傳做好準備。

創(chuàng)立文件上傳控制器

初始應(yīng)用程序現(xiàn)已包括一些類來處理在磁盤上存儲和加載上傳的文件。它們都坐落
com.example.uploadingfiles.storage包裝中。您將在新的FileUploadController. 以下清單(來自
src/main/java/com/example/uploadingfiles/FileUploadController.java)顯現(xiàn)了文件上傳控制器:

package com.example.uploadingfiles; import java.io.IOException; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.example.uploadingfiles.storage.StorageFileNotFoundException; import com.example.uploadingfiles.storage.StorageService; @Controller public class FileUploadController {  private final StorageService storageService;  @Autowired  public FileUploadController(StorageService storageService) {  this.storageService = storageService;  }  @GetMapping("/")  public String listUploadedFiles(Model model) throws IOException {  model.addAttribute("files", storageService.loadAll().map(  path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,  "serveFile", path.getFileName().toString()).build().toUri().toString())  .collect(Collectors.toList()));  return "uploadForm";  }  @GetMapping("/files/{filename:.+}")  @ResponseBody  public ResponseEntityserveFile(@PathVariable String filename) {  Resource file = storageService.loadAsResource(filename);  return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,  "attachment; filename=\"" + file.getFilename() + "\"").body(file);  }  @PostMapping("/")  public String handleFileUpload(@RequestParam("file") MultipartFile file,  RedirectAttributes redirectAttributes) {  storageService.store(file);  redirectAttributes.addFlashAttribute("message",  "You successfully uploaded " + file.getOriginalFilename() + "!");  return "redirect:/";  }  @ExceptionHandler(StorageFileNotFoundException.class)  public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {  return ResponseEntity.notFound().build();  } }

該類FileUploadController帶有注釋,@Controller以便 Spring MVC 能夠拾取它并查找路由。每個辦法都被標記@GetMapping或@PostMapping將途徑和 HTTP 操作綁定到特定的控制器操作。

在這種情況下:

  • GET /:從 中查找當前上傳文件的列表StorageService并將其加載到 Thymeleaf 模板中。它經(jīng)過運用 計算到實際資源的鏈接MvcUriComponentsBuilder。
  • GET /files/{filename}:加載資源(假如存在)并運用Content-Disposition呼應(yīng)頭將其發(fā)送到瀏覽器進行下載。
  • POST /:處理多部分音訊file并將其供給給StorageService保存。

在出產(chǎn)場景中,您更有可能將文件存儲在暫時位置、數(shù)據(jù)庫或 NoSQL 存儲(例如Mongo 的 GridFS)中。最好不要在應(yīng)用程序的文件體系中加載內(nèi)容。

您將需求供給一個StorageService以便控制器能夠與存儲層(例如文件體系)進行交互。以下清單(來自
src/main/java/com/example/uploadingfiles/storage/StorageService.java)顯現(xiàn)了該界面:

package com.example.uploadingfiles.storage; import org.springframework.core.io.Resource; import org.springframework.web.multipart.MultipartFile; import java.nio.file.Path; import java.util.stream.Stream; public interface StorageService {  void init();  void store(MultipartFile file);  StreamloadAll();  Path load(String filename);  Resource loadAsResource(String filename);  void deleteAll(); }

創(chuàng)立 HTML 模板

以下 Thymeleaf 模板(來自
src/main/resources/templates/uploadForm.html)顯現(xiàn)了怎么上傳文件并顯現(xiàn)已上傳內(nèi)容的示例:

 
				

File to upload:

該模板包括三個部分:

調(diào)整文件上傳限制

裝備文件上傳時,設(shè)置文件巨細限制通常很有用?;孟胍幌聡L試處理 5GB 文件上傳!MultipartConfigElement運用 Spring Boot,咱們能夠運用一些特點設(shè)置來調(diào)整它的主動裝備。

將以下特點增加到現(xiàn)有特點設(shè)置(在 中
src/main/resources/application.properties):

多部分設(shè)置的束縛如下:

運轉(zhuǎn)應(yīng)用程序

您需求一個方針文件夾來上傳文件,因而您需求增強UploadingFilesApplicationSpring Initializr 創(chuàng)立的基本類并增加一個 BootCommandLineRunner以在發(fā)動時刪除并重新創(chuàng)立該文件夾。以下清單(來自
src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java)顯現(xiàn)了怎么履行此操作:

@SpringBootApplication是一個方便的注釋,它增加了以下一切內(nèi)容:

該main()辦法運用 Spring Boot 的SpringApplication.run()辦法來發(fā)動應(yīng)用程序。您是否注意到?jīng)]有一行 XML?也沒有web.xml文件。這個 Web 應(yīng)用程序是 100% 純 Java,您不必處理任何管道或基礎(chǔ)設(shè)施的裝備。

構(gòu)建一個可履行的 JAR

您能夠運用 Gradle 或 Maven 從命令行運轉(zhuǎn)應(yīng)用程序。您還能夠構(gòu)建一個包括一切必要依靠項、類和資源的單個可履行 JAR 文件并運轉(zhuǎn)它。構(gòu)建可履行 jar 能夠在整個開發(fā)生命周期、跨不同環(huán)境等中輕松地作為應(yīng)用程序交付、版本化和部署服務(wù)。

假如您運用 Gradle,則能夠運用./gradlew bootRun. 或者,您能夠運用構(gòu)建 JAR 文件./gradlew build,然后運轉(zhuǎn) JAR 文件,如下所示:

假如您運用 Maven,則能夠運用./mvnw spring-boot:run. 或者,您能夠運用構(gòu)建 JAR 文件,./mvnw clean package然后運轉(zhuǎn)該 JAR 文件,如下所示:

此處描繪的進程創(chuàng)立了一個可運轉(zhuǎn)的 JAR。您還能夠構(gòu)建經(jīng)典的 WAR 文件。

它運轉(zhuǎn)接納文件上傳的服務(wù)器端部分。顯現(xiàn)記錄輸出。該服務(wù)應(yīng)在幾秒鐘內(nèi)發(fā)動并運轉(zhuǎn)。

在服務(wù)器運轉(zhuǎn)的情況下,您需求翻開瀏覽器并訪問http://localhost:8080/以查看上傳表單。挑選一個(?。┪募?,然后按Upload。您應(yīng)該會從控制器中看到成功頁面。假如你挑選的文件太大,你會得到一個丑惡的錯誤頁面。

然后,您應(yīng)該會在瀏覽器窗口中看到類似于以下內(nèi)容的行:

“您成功上傳了<文件名>!”

測驗?zāi)膽?yīng)用程序

有多種辦法能夠在咱們的應(yīng)用程序中測驗此特定功用。以下清單(來自
src/test/java/com/example/uploadingfiles/FileUploadTests.java)顯現(xiàn)了一個示例,MockMvc它不需求發(fā)動 servlet 容器:

package com.example.uploadingfiles; import java.nio.file.Paths; import java.util.stream.Stream; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.example.uploadingfiles.storage.StorageFileNotFoundException; import com.example.uploadingfiles.storage.StorageService; @AutoConfigureMockMvc @SpringBootTest public class FileUploadTests {  @Autowired  private MockMvc mvc;  @MockBean  private StorageService storageService;  @Test  public void shouldListAllFiles() throws Exception {  given(this.storageService.loadAll())  .willReturn(Stream.of(Paths.get("first.txt"), Paths.get("second.txt")));  this.mvc.perform(get("/")).andExpect(status().isOk())  .andExpect(model().attribute("files",  Matchers.contains("http://localhost/files/first.txt",  "http://localhost/files/second.txt")));  }  @Test  public void shouldSaveUploadedFile() throws Exception {  MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt",  "text/plain", "Spring Framework".getBytes());  this.mvc.perform(multipart("/").file(multipartFile))  .andExpect(status().isFound())  .andExpect(header().string("Location", "/"));  then(this.storageService).should().store(multipartFile);  }  @SuppressWarnings("unchecked")  @Test  public void should404WhenMissingFile() throws Exception {  given(this.storageService.loadAsResource("test.txt"))  .willThrow(StorageFileNotFoundException.class);  this.mvc.perform(get("/files/test.txt")).andExpect(status().isNotFound());  } }

在這些測驗中,您運用各種模擬來設(shè)置與您的控制器以及StorageService與 Servlet 容器本身的交互,運用MockMultipartFile.

有關(guān)集成測驗的示例,請參見
FileUploadIntegrationTests類(坐落 中
src/test/java/com/example/uploadingfiles)。

概括

恭喜!您剛剛編寫了一個運用 Spring 處理文件上傳的 Web 應(yīng)用程序。