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

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Spring REST Multipart – 多部分上傳示例 > 原文: [https://howtodoinjava.com/spring-restful/multipart-multiple-uploads-example/](https://howtodoinjava.com/spring-restful/multipart-multiple-uploads-example/) 了解如何使用 Spring REST API 接受**上傳多個多部分**二進制文件(例如 jpeg 圖像),這些文件接受[`MultipartFile`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html)請求的數組。 ## 1\. Maven 依賴 除了 [spring webmvc](https://howtodoinjava.com/spring-mvc-tutorial/) 之外,我們還將在類路徑中需要[`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="1000000"/> </bean> ... </beans> ``` 等效的 Java 注解配置為: ```java @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(20848820); return multipartResolver; } ``` ## 3\. 創建多部分上載 Rest API 創建給定的 [REST API](http://restfulapi.net/) ,該 API 將負責處理發布到服務器的多個上載。 在給出的示例中,我在路徑`/employee-management/employees/1/photo/multiple`處創建了 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; } @PostMapping(value = "/multiple", consumes = { "multipart/form-data" }) Callable<ResponseEntity<?>> writeMultiple(@PathVariable Long id, @RequestParam("files") MultipartFile[] files) throws Exception { return () -> this.repository.findById(id).map(employee -> { Arrays.asList(files).stream().forEach(file -> { File fileForEmployee; try { fileForEmployee = uploadPath(employee, file); } catch (IOException e) { throw new RuntimeException(e); } try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(fileForEmployee)) { FileCopyUtils.copy(in, out); } catch (IOException ex) { throw new RuntimeException(ex); } }); return ResponseEntity.ok().build(); }).orElseThrow(() -> new RecordNotFoundException("Employee id is not present in database")); } private File uploadPath(Employee e, MultipartFile file) throws IOException { File uploadPath = Paths.get(this.uploadDirRoot.getPath(), e.getId().toString()).toFile(); if(uploadPath.exists() == false) { uploadPath.mkdirs(); } return new File(uploadPath.getAbsolutePath(), file.getOriginalFilename()); } } ``` 如果文件系統中尚不存在上述 REST 控制器,則會創建一個上載文件夾(名稱為員工 ID)。 仍然需要定義以下屬性。 `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 頁面,其中僅包含文件類型的多個字段。 我們將從計算機瀏覽一些圖像,并將其上傳到服務器。 `multipleFileUpload.jsp` ```java <html> <head> <title>Spring REST File Upload</title> </head> <body> <form method="POST" action="/SpringRestExample/api/rest/employee-management/employees/1/photo/multiple" enctype="multipart/form-data"> <table> <tr> <td>Select first file to upload</td> <td><input type="file" name="files" /></td> </tr> <tr> <td>Select second file to upload</td> <td><input type="file" name="files" /></td> </tr> <tr> <td>Select third file to upload</td> <td><input type="file" name="files" /></td> </tr> <tr> <td><input type="submit" value="Submit" /></td> </tr> </table> </form> </body> </html> ``` 現在啟動服務器并在 URL `http://localhost:8080/SpringRestExample/multipleFileUpload.jsp`中打開上傳頁面。 瀏覽圖像,然后單擊提交按鈕。 圖像文件將被上傳到配置的上傳目錄中的服務器。 要下載文件,請在瀏覽器中輸入 URL `/employee-management/employees/1/photo`,然后將顯示圖像。 下載 API 已包含在附件中。 請問您有關創建 **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>

                              哎呀哎呀视频在线观看