<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Spring REST – 多部分上傳和下載示例 > 原文: [https://howtodoinjava.com/spring-restful/multipart-upload-download-example/](https://howtodoinjava.com/spring-restful/multipart-upload-download-example/) 了解如何使用接受[`MultipartFile`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html)請求的 Spring REST API **上傳多部分**二進制文件(例如 jpeg 圖像)。 還學習使用[`FileSystemResource`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/FileSystemResource.html)使用另一個 REST API 下載文件。 ## 1\. Maven 依賴 除了 spring webmvc 之外,我們在類路徑中還需要[`commons-fileupload`](https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload)和[`commons-io`](https://mvnrepository.com/artifact/commons-io/commons-io)。 `pom.xml` ```java dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.6.RELEASE</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> ``` ## 2\. 配置`CommonsMultipartResolver` 它是`commons-fileupload`的基于 Servlet 的[`MultipartResolver`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/commons/CommonsMultipartResolver.html)實現。 它提供`maxUploadSize`,`maxInMemorySize`和`defaultEncoding`設置作為 bean 屬性。 此類的目的是將臨時文件保存到 [Servlet](https://howtodoinjava.com/servlets/complete-java-servlets-tutorial/) 容器的臨時目錄中。 `rest-servlet.xml` ```java <beans> ... <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="100000"/> </bean> ... </beans> ``` ## 3\. 創建多部分處理器 API 創建兩個 [REST API](http://restfulapi.net/) ,它們將負責處理上載和下載請求以及響應。 在給出的示例中,我在路徑`/employee-management/employees/1/photo`處創建了 API。 我假設 ID 為`'1'`的員工存在于數據庫中。 隨時更改資源路徑和實現。 `EmployeeImageController.java` ```java package com.howtodoinjava.demo.controller; import static org.springframework.web.servlet .support.ServletUriComponentsBuilder.fromCurrentRequest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.util.concurrent.Callable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; 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.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.howtodoinjava.demo.exception.RecordNotFoundException; import com.howtodoinjava.demo.model.Employee; import com.howtodoinjava.demo.repository.EmployeeRepository; @RestController @RequestMapping(value = "/employee-management/employees/{id}/photo") @PropertySource("classpath:application.properties") public class EmployeeImageController { @Autowired private EmployeeRepository repository; private File uploadDirRoot; @Autowired EmployeeImageController(@Value("${image.upload.dir}") String uploadDir, EmployeeRepository repository) { this.uploadDirRoot = new File(uploadDir); this.repository = repository; } @GetMapping ResponseEntity<Resource> read(@PathVariable Long id) { return this.repository.findById(id) .map(employee -> { File file = fileFor(employee); Resource fileSystemResource = new FileSystemResource(file); return ResponseEntity.ok() .contentType(MediaType.IMAGE_JPEG) .body(fileSystemResource); }) .orElseThrow(() -> new RecordNotFoundException("Image for available")); } @RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, consumes = { "multipart/form-data" }) Callable<ResponseEntity<?>> write(@PathVariable Long id, @RequestParam("file") MultipartFile file) throws Exception { return () -> this.repository.findById(id) .map(employee -> { File fileForEmployee = fileFor(employee); try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(fileForEmployee)) { FileCopyUtils.copy(in, out); } catch (IOException ex) { throw new RuntimeException(ex); } URI location = fromCurrentRequest().buildAndExpand(id).toUri(); return ResponseEntity.created(location).build(); }) .orElseThrow(() -> new RecordNotFoundException("Employee id is not present in database")); } private File fileFor(Employee e) { return new File(this.uploadDirRoot, Long.toString(e.getId())); } } ``` 上面的 REST 控制器依賴于**上傳文件夾**即`image.upload.dir`配置在屬性文件中的存在。 `application.properties` ```java image.upload.dir=c:/temp/images ``` 同樣,控制器返回可調用的 **[](https://howtodoinjava.com/java/multi-threading/java-callable-future-example/)**,這意味著該方法將在 IO 操作可能運行時立即返回。 上傳過程完成后,API 將返回響應。 要**啟用異步支持**,請在[`DispatcherServlet`](https://howtodoinjava.com/spring5/webmvc/spring-dispatcherservlet-tutorial/)中配置**異步支持的**。 `web.xml` ```java <web-app> <display-name>Employee Management REST APIs</display-name> <servlet> <servlet-name>rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>/api/rest/*</url-pattern> </servlet-mapping> </web-app> ``` ## 4\. 多部分上傳請求演示 出于演示目的,我創建了一個 JSP 頁面,其中僅包含一個類型的文件字段。 我們將從計算機瀏覽圖像,并將其上傳到服務器。 `singleFileUpload.jsp` ```java <html> <head> <title>Spring REST File Upload</title> </head> <body> <form method="POST" action="/SpringRestExample/api/rest/employee-management/employees/1/photo" enctype="multipart/form-data"> <table> <tr> <td>Select a file to upload</td> <td><input type="file" name="file" /></td> </tr> <tr> <td><input type="submit" value="Submit" /></td> </tr> </table> </form> </body> </html> ``` 現在啟動服務器并在 URL `http://localhost:8080/SpringRestExample/singleFileUpload.jsp`中打開上傳頁面。 瀏覽文件,然后單擊提交按鈕。 圖像文件將被上傳到配置的上傳目錄中的服務器。 要下載文件,請在瀏覽器中輸入 URL `/employee-management/employees/1/photo`,然后將顯示圖像。 請問您有關創建 **Spring MVC REST API 來處理多部分文件上傳和下載**的問題。 [下載源碼](https://howtodoinjava.com/wp-content/downloads/SpringRestMultiPartExample.zip) 學習愉快!
                  <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>

                              哎呀哎呀视频在线观看