<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 MVC 多文件上傳示例 > 原文: [https://howtodoinjava.com/spring-mvc/spring-mvc-multi-file-upload-example/](https://howtodoinjava.com/spring-mvc/spring-mvc-multi-file-upload-example/) Spring MVC 為任何應用程序中的**多文件上傳**功能提供了開箱即用的支持。 本教程使用[`CommonsMultipartResolver`](https://docs.spring.io/autorepo/docs/spring-framework/4.2.6.RELEASE/javadoc-api/org/springframework/web/multipart/commons/CommonsMultipartResolver.html),并且需要[ apache commons 文件上載](https://commons.apache.org/proper/commons-fileupload/)和 [apache commons io](https://commons.apache.org/proper/commons-io/) 依賴項。 `pom.xml` ```java <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> ``` ## 1\. Spring MVC `MultipartFile`接口 上傳到 Spring MVC 應用程序的文件將包裝在[`MultipartFile`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartFile.html)對象中。 我們需要做的就是編寫一個屬性類型為`MultipartFile`的域類。 該界面具有獲取上傳文件的名稱和內容的方法,例如 `getBytes()`,`getInputStream()`,`getOriginalFilename()`, `getSize()`,`isEmpty()`和`tranferTo()`。 例如,要將上傳的文件保存到文件系統,我們可以使用`transferTo`方法: `文件上傳到文件系統` ```java File file = new File(...); multipartFile.transferTo(file); ``` ## 2\. 用于文件上傳的域類 您需要創建一個具有必要屬性的簡單域類,并創建一個用于存儲`List<MultipartFile>`類型的文件的域類。 為了構建此示例,我編寫了此域類。 `Product.java` ```java public class Product implements Serializable { private static final long serialVersionUID = 74458L; @NotNull @Size(min=1, max=10) private String name; private String description; private List<MultipartFile> images; //getters and setters } ``` ## 3\. Spring MVC 多文件上傳控制器 在控制器類中,我們將在域類中獲取上載文件的預填充詳細信息。 只需獲取詳細信息,然后根據應用程序設計將文件存儲在文件系統或數據庫中即可。 `DemoProductController.java` ```java @Controller public class DemoProductController { @RequestMapping("/save-product") public String uploadResources( HttpServletRequest servletRequest, @ModelAttribute Product product, Model model) { //Get the uploaded files and store them List<MultipartFile> files = product.getImages(); List<String> fileNames = new ArrayList<String>(); if (null != files && files.size() > 0) { for (MultipartFile multipartFile : files) { String fileName = multipartFile.getOriginalFilename(); fileNames.add(fileName); File imageFile = new File(servletRequest.getServletContext().getRealPath("/image"), fileName); try { multipartFile.transferTo(imageFile); } catch (IOException e) { e.printStackTrace(); } } } // Here, you can save the product details in database model.addAttribute("product", product); return "viewProductDetail"; } @RequestMapping(value = "/product-input-form") public String inputProduct(Model model) { model.addAttribute("product", new Product()); return "productForm"; } } ``` ## 4\. Spring MVC 配置更改 為了支持**多部分請求**,我們需要在配置文件中聲明`multipartResolver` bean。 `beans.xml` ```java <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20848820" /> </bean> ``` 等效的 Java **注解配置**為: ```java @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(20848820); return multipartResolver; } ``` 此外,我們可能希望將服務器上的文件存儲路徑映射為資源。 這將是 spring mvc 文件上傳目錄。 ```java <mvc:resources mapping="/image/**" location="/image/" /> ``` 本示例使用的完整配置文件為: `beans.xml` ```java <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context/ http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.howtodoinjava.demo" /> <mvc:resources mapping="/image/**" location="/image/" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20848820" /> </bean> </beans> ``` ## 5\. Spring MVC 視圖上傳文件 我已經寫了兩個 JSP 文件。 一個用于顯示文件上傳表單,用戶將在其中填寫其他詳細信息并選擇要上傳的文件。 其次,我們將顯示帶有其他詳細信息的上傳文件。 `productForm.jsp` ```java <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title>Add Product Form</title> </head> <body> <div id="global"> <form:form commandName="product" action="save-product" method="post" enctype="multipart/form-data"> <fieldset> <legend>Add a product</legend> <p> <label for="name">Product Name: </label> <form:input id="name" path="name" cssErrorClass="error" /> <form:errors path="name" cssClass="error" /> </p> <p> <label for="description">Description: </label> <form:input id="description" path="description" /> </p> <p> <label for="image">Product Images: </label> <input type="file" name="images" multiple="multiple"/> </p> <p id="buttons"> <input id="reset" type="reset" tabindex="4"> <input id="submit" type="submit" tabindex="5" value="Add Product"> </p> </fieldset> </form:form> </div> </body> </html> ``` `viewProductDetail.jsp` ```java <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <title>Save Product</title> </head> <body> <div id="global"> <h4>The product has been saved.</h4> <h5>Details:</h5> Product Name: ${product.name}<br/> Description: ${product.description}<br/> <p>Following files are uploaded successfully.</p> <ol> <c:forEach items="${product.images}" var="image"> <li>${image.originalFilename} <img width="100" src="<c:url value="/image/"/>${image.originalFilename}"/> </li> </c:forEach> </ol> </div> </body> </html> ``` ## Spring MVC 多文件上傳示例 當我們用`http://localhost:8080/springmvcexample/product-input-form`進入瀏覽器時,我們得到以下屏幕: ![Spring MVC file upload form](https://img.kancloud.cn/0f/fe/0ffebdca646551e4d87b1af5dfa5ac46_370x234.jpg) Spring MVC 文件上傳表單 我們填寫詳細信息并提交表格,我們將在其他頁面中獲取提交的詳細信息和所有上傳的文件: ![file uploaded successfully](https://img.kancloud.cn/d1/bf/d1bf1ff759cb22d99d3709caed852e48_334x370.jpg) 文件成功上傳 在與 **spring mvc 多文件上傳示例**相關的評論部分中,向我提出您的問題和建議。 學習愉快!
                  <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>

                              哎呀哎呀视频在线观看