<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 在 ajax 和 jquery 中使用進度條上傳多個文件 > 原文: [https://howtodoinjava.com/spring-mvc/spring-mvc-multi-file-upload-with-progress-bar/](https://howtodoinjava.com/spring-mvc/spring-mvc-multi-file-upload-with-progress-bar/) 此 **Spring MVC** 示例演示了如何在進度條中使用**多文件上傳**功能,而服務器端代碼是用 Spring MVC 編寫的。 我已經修改了[ spring MVC 多文件上傳示例](https://howtodoinjava.com/spring/spring-mvc/spring-mvc-multi-file-upload-example/)上一篇文章的代碼,該示例沒有**進度欄**功能,而是在新的顯示頁面上顯示了上傳的圖像和數據。 本示例使用純 JavaScript 代碼和 HTML5 控件來構建客戶端代碼。 如果您想使用任何 JavaScript 庫,例如 jQuery 然后請相應地修改代碼。 ## 1\. 文件上傳和進度欄的客戶端視圖 在下面的`productForm.jsp`中給出了 spring MVC 項目中的 JSP 文件-但它僅包含 HTML 代碼,因此如果您愿意,可以輕松地放置相同的代碼。 該文件具有`onUploadProgress()`函數,該函數顯示上傳文件的進度。 還有其他功能可以顯示上載過程和支持活動的完成情況。 `productForm.jsp` ```java <!DOCTYPE html> <html> <head> <script> var totalFileLength, totalUploaded, fileCount, filesUploaded; //To log everything on console function debug(s) { var debug = document.getElementById('debug'); if (debug) { debug.innerHTML = debug.innerHTML + '<br/>' + s; } } //Will be called when upload is completed function onUploadComplete(e) { totalUploaded += document.getElementById('files').files[filesUploaded].size; filesUploaded++; debug('complete ' + filesUploaded + " of " + fileCount); debug('totalUploaded: ' + totalUploaded); if (filesUploaded < fileCount) { uploadNext(); } else { var bar = document.getElementById('bar'); bar.style.width = '100%'; bar.innerHTML = '100% complete'; alert('Finished uploading file(s)'); } } //Will be called when user select the files in file control function onFileSelect(e) { var files = e.target.files; // FileList object var output = []; fileCount = files.length; totalFileLength = 0; for (var i = 0; i < fileCount; i++) { var file = files[i]; output.push(file.name, ' (', file.size, ' bytes, ', file.lastModifiedDate.toLocaleDateString(), ')'); output.push('<br/>'); debug('add ' + file.size); totalFileLength += file.size; } document.getElementById('selectedFiles').innerHTML = output.join(''); debug('totalFileLength:' + totalFileLength); } //This will continueously update the progress bar function onUploadProgress(e) { if (e.lengthComputable) { var percentComplete = parseInt((e.loaded + totalUploaded) * 100 / totalFileLength); var bar = document.getElementById('bar'); bar.style.width = percentComplete + '%'; bar.innerHTML = percentComplete + ' % complete'; } else { debug('unable to compute'); } } //the Ouchhh !! moments will be captured here function onUploadFailed(e) { alert("Error uploading file"); } //Pick the next file in queue and upload it to remote server function uploadNext() { var xhr = new XMLHttpRequest(); var fd = new FormData(); var file = document.getElementById('files').files[filesUploaded]; fd.append("multipartFile", file); xhr.upload.addEventListener("progress", onUploadProgress, false); xhr.addEventListener("load", onUploadComplete, false); xhr.addEventListener("error", onUploadFailed, false); xhr.open("POST", "save-product"); debug('uploading ' + file.name); xhr.send(fd); } //Let's begin the upload process function startUpload() { totalUploaded = filesUploaded = 0; uploadNext(); } //Event listeners for button clicks window.onload = function() { document.getElementById('files').addEventListener('change', onFileSelect, false); document.getElementById('uploadButton').addEventListener('click', startUpload, false); } </script> </head> <body> <div style="width:55%"> <h1>HTML5 Ajax Multi-file Upload With Progress Bar</h1> <div id='progressBar' style='height: 20px; border: 2px solid green; margin-bottom: 20px'> <div id='bar' style='height: 100%; background: #33dd33; width: 0%'> </div> </div> <form style="margin-bottom: 20px"> <input type="file" id="files" multiple style="margin-bottom: 20px"/><br/> <output id="selectedFiles"></output> <input id="uploadButton" type="button" value="Upload" style="margin-top: 20px"/> </form> <div id='debug' style='height: 100px; border: 2px solid #ccc; overflow: auto'></div> </div> </body> </html> ``` ## 2\. 討論上傳進度功能 上面的代碼足以說明問題,您在理解上應該不會遇到任何問題。 但是,讓我們總結一下要點: 1. **“上傳”** 按鈕不是提交按鈕。 因此,單擊它不會提交包含表單。 實際上,該腳本使用`XMLHttpRequest`對象進行上傳。 2. `totalFileLength`變量保存要上傳的文件的總長度。 `totalUploaded`是到目前為止已上傳的字節數。 `fileCount`包含要上傳的文件數,`filesUploaded`指示已上傳的文件數。 3. `window.onload()`使用`onFileSelect`功能映射文件輸入元素的**更改**事件,并使用`startUpload`映射按鈕的**單擊**事件。 4. 當用戶單擊“上傳”按鈕時,將調用`startUpload`函數,然后依次調用`uploadNext`函數。 `uploadNext`上傳所選文件集中的下一個文件。 首先創建一個`XMLHttpRequest`對象和一個`FormData`對象,接下來要上載的文件將附加到該對象。 5. 然后,`uploadNext`函數將`XMLHttpRequest`對象的**進度**事件附加到`onUploadProgress`和`load`事件,并將`error`事件附加到`onUploadComplete`和`onUploadFailed`。 6. 在上載進度期間,會反復調用`onUploadProgress`功能,從而有機會更新進度條。 7. 上載完成后,將調用`onUploadComplete`函數。 ## 3\. 多個文件上傳控制器和模型類 Spring MVC 文件上傳控制器和模型類如下所示: #### 3.1. Spring MVC 多文件上傳控制器 `DemoProductController.java` ```java package com.howtodoinjava.demo.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import com.howtodoinjava.demo.model.UploadedFile; @Controller public class DemoProductController { @RequestMapping("/save-product") public void saveFile(HttpServletRequest servletRequest, @ModelAttribute UploadedFile uploadedFile, BindingResult bindingResult, Model model) { MultipartFile multipartFile = uploadedFile.getMultipartFile(); String fileName = multipartFile.getOriginalFilename(); try { File file = new File(servletRequest.getServletContext().getRealPath("/image"), fileName); multipartFile.transferTo(file); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping(value = "/product-input-form") public String inputProduct(Model model) { return "productForm"; } } ``` #### 3.2. Spring MVC 多文件模型類 `UploadedFile.java` ```java package com.howtodoinjava.demo.model; import org.springframework.web.multipart.MultipartFile; public class UploadedFile { private static final long serialVersionUID = 1L; private MultipartFile multipartFile; public MultipartFile getMultipartFile() { return multipartFile; } public void setMultipartFile(MultipartFile multipartFile) { this.multipartFile = multipartFile; } } ``` ## 4\. 用于構建示例的其他文件 #### 4.1. `web.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <display-name>Spring Web MVC Hello World Application</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <multipart-config> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> <file-size-threshold>1048576</file-size-threshold> </multipart-config> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` #### 4.2. `spring-servlet.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.support.StandardServletMultipartResolver"></bean> </beans> ``` ## 5\. Spring MVC 多個文件上傳,帶有進度條演示 * 點擊 URL: `http://localhost:8080/springmvcexample/product-input-form` 下面的屏幕將在瀏覽器上加載。 ![Multi-file Upload With Progress Bar - Input Form](https://img.kancloud.cn/0d/a7/0da7f064071682bb18c7b5a41dfa3920_748x380.jpg) 帶有進度條的多文件上傳 - 輸入表單 * 選擇文件,然后單擊上載按鈕 * 如果一切正常,那么您將獲得如下所示的上傳進度欄和上傳的文件信息。 ![Multi-file Upload With Progress Bar - Upload Success](https://img.kancloud.cn/84/bd/84bd3a8587632aeebe6e82d6a30cadb9_757x546.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>

                              哎呀哎呀视频在线观看