Есть два способа реализации многопрофильной загрузки в SpringMVC. Одним из них является загрузка файлов в байтовом потоке, которые мы часто используем, а другой - загружать их, используя анализатор, завернутый в SpringMVC. Эти два метода имеют большой пробел в эффективности достижения многопрофильной загрузки. Давайте посмотрим на методы реализации этих двух методов с помощью примеров и сравним, насколько большой разрыв в эффективности существует.
1. Загрузите соответствующий пакет JAR. В дополнение к пакету JAR SpringMVC, com.springsource.org.apache.commons.fileupload-1.2.0.jar и com.springsource.org.apache.commons.io-1.4.0.jar и com.springsource.org.apache.commons.io-14.0.jar также необходимы.
2. Настройте файл Springannotation-servlet.xml (имя файла можно настроить, если он совпадает с именем, представленным в Web.xml):
<? xml version = "1.0" Encoding = "UTF-8"?> <!-Header Bean-> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "htttp://www.w3 xmlns: p = "http://www.springframework.org/schema/p" xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: context = "http://www.springframe.orgema. xmlns: util = "http://www.springframework.org/schema/util" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.spramework.orgemabema/beans/spring.3.0.spring-3.0.spring-3.0.spring-3.0.spring-3.0.spring-3.0.spring-3. http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd "> <! base-package = "com.tgb.web.controller.annotation"> </context: component-scan> <!-Заменить следующие две строки кода-> <MVC: Annotation-infiven/> <!-Статический доступ к ресурсам-> <MVC: Resources Location = "/"/"MAPPING ="/IMG/** "/> <MVC: Resources ="/JS/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/"/IMG/** "/"/"/"/"/"/"/"/"/"/IMG/** "/"/"/"/"/" MAPPIN mapping = "/js/**"/> <bean id = "viewresolver"> <name = "prefix" value = "/"> </property> <name = "суффикс" value = ". jsp"> </property> </bean> <bean id = "multiartresolver"> name = "defaultencoding" value = "utf-8"> </itproport> </property> </itprotport> </property> </itproportulver> </property "> <//". name = "maxuploadSize" value = "10485760000"> </property> <name = "maxinMemorySize" value = "40960"> </property> </bean> </beans>
3. Настройте файл web.xml:
<? xml version = "1.0" Encoding = "utf-8"?> <web-app xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "webapp_id" version = "2,5"> <Slace-Name> springmvc1 </warepaP_ID "2,5"> <Slame-Name> <slownist> <welcelporting> index.html </wervedied-file> </werveding-file-list> <servlet> <vervlet-name> springmvc </servlet-name> <!-Springmvc Distributor-> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <initparame> <param-name-nlameconcerer grame-contameconcererervelcerererverervelcererervel <param-value>classpath*:config/springAnnotation-servlet.xml</param-value> </init-param> <!-- Indicates that the Servlet is initialized when Tomcat is started --> <load-on-startup>1</load-on-startup> </servlet> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filter> <init-param> <param-name> кодирование </param-name> <value> utf-8 </param-value> <!-Установите набор символов, который вы хотите использовать. Я использую GB18030-> </init-param> <init-param> <param-ale> forceEncoding </param-name> <value> true </param-value> </init-param> </filter> <Filter-MAPPIN Чтобы фильтровать, настройте его в соответствии с вашими потребностями-> </filter-mapping> <servlet-mapping> <servlet-name> springmvc </servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4. Код страницы JSP:
<%@ page language = "java" contentType = "text/html; charset = utf-8" pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtd html 4.01 transitional // en" http://www.w3.org/tml4/html4/html. <html> <head> <script type = "text/javascript" src = "../ js/jquery-1.7.2.js"> </script> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"> <Tite> insert tit J = 1; $ (document) .ready (function () {$ ("#btn_add1"). click (function () {document.getElementById ("newUpload1"). innerHtml+= '<div id = "div _'+i+'"> <input name = "file =" file " /> <input =" value = "delete" onclick = "del_1 ('+i+')"/> </div> '; /> <input type = "value =" delete " function del_1 (o) {document.getElementById ("newUpload1"). RemoveChild (document.getElementById ("div _"+O)); } function del_2 (o) {document.getElementById ("newUpload2"). RemoveChild (document.getElementById ("div _"+O)); } </script> </head> <body> <h1>springMVC byte stream input upload file</h1> <form name="userForm1" action="/springMVC7/file/upload" enctype="multipart/form-data" method="post"> <div id="newUpload1"> <input type="file" name="file"> </div> <input type="button" id = "btn_add1" value = "Добавить одну строку"> <input type = "propect" value = "upload"> </form> <br> <hr align = "left" color = "#ff0000" size = "3"> <br> <h1> springmvc class class class file </h1> <form name = "userform2" action = "/springmv -файл"/waplight7 "oplugle7/springmv7/opludg7"/springmv7/oplugle7 "/springmv7/oplugle7/springmv7" oplugle7 "/springmv. ectype = "multipart/form-data" method = "post" "> <div id =" newupload2 "> <input type =" file "name =" file "> </div> <input type =" button "id =" btn_add2 "value =" Добавить одну строку "> <input value =" upload "> </form> </body> </html> </html> </html> </html> </html> </html> </html> </html> </html> </html> </html> </html> </html> </html> </html>5. Java Bean, который реализует функцию загрузки:
пакет com.tgb.web.controller.annotation.upload; Импорт java.io.file; импортировать java.io.fileinputstream; Импорт java.io.fileOutputStream; импортировать java.io.ioexception; Импорт java.io.printwriter; импортировать java.io.unsupportedencodingexception; импортировать java.net.urldecoder; импортировать java.util.date; импортировать java.util.iterator; Импорт javax.servlet.http.httpservletrequest; Импорт javax.servlet.http.httpservletresponse; Импорт javax.swing.filechooser.filenameeextensionfilter; Import org.springframework.sterotype.controller; Импорт org.springframework.web.bind.annotation.requestmapping; Импорт org.springframework.web.bind.annotation.requestmethod; Импорт org.springframework.web.bind.annotation.requestparam; Импорт org.springframework.web.multipart.multipartfile; Импорт org.springframework.web.multipart.multiparthttpservletrequest; Import org.springframework.web.multipart.commons.commonsmultipartfile; Импорт org.springframework.web.multipart.commons.commonsmultipartresolver; Импорт org.springframework.web.servlet.modelandView; Импорт com.tgb.web.controller.entity.user; @Controller @RequestMapping ("/file") открытый класс uploadController {@RequestMapping ("/upload") public String AddUser (@RequestParam ("file") CommonsMultiPartFile [] файлы, httpservletrequest) {для (int i = 0; System.out.println ("filename ----------->" + files [i] .getoriginalfilename ()); if (! files [i] .isempty ()) {int pre = (int) System.currentTimeMillis (); try {// Получить выходной поток и переименовать загруженный файл fileOutputStream OS = new FileOutputStream ("h:/" + new Date (). getTime () + files [i] .getoriginalFilename ()); // Получить поток ввода загруженного файла файла fileInputStream in = (fileInputStream) файлов [i] .getInputStream (); // написать файл int b = 0; while ((b = in.read ())! = -1) {os.write (b); } os.flush (); os.close (); in.close (); int final Time = (int) System.CurrentTimeMiMillis (); System.out.println (finaltime - pre); } catch (Exception e) {e.printstackTrace (); System.out.println ("uploadError"); }}} return "/success"; } @RequestMapping ("/upload2") public String upload2 (запрос httpservletrequest, httpservletresponse response) Throws allodalStateException, ioException {// Создание общего многообразного резолвера // защищать, имеет ли запрос загрузку файла, то есть if (multipResolver.ismultipart (request)) {// конвертировать в Multipart Request MultiprthttpLERSERVLERQUEST multireQuest = (MultipRTHTTPServLectleRQUEST) запрос; // Получить все имена файлов в запросе iterator <string> iter = multirequest.getFilenames (); while (iter.hasnext ()) {// Запишите время в начале процесса загрузки и используйте его для вычисления времени загрузки int pre = (int) system.currenttimemillis (); // Получить файл upload multiplectfile file = multirequest.getFile (iter.next ()); if (file! = null) {// Получить имя файла загруженной в настоящее время строки файла myfilEname = file.getoriginalfilename (); // Если имя не является «», это означает, что файл существует, в противном случае это означает, что файл не существует, если (myfilename.trim ())! = "") {System.out.println (myFilEname); // Переименование загруженного имени файла string fileName = "demoupload" + file.getoriginalfilename (); // Определите путь пути загрузки String = "h:/" + filename; File localfile = new File (path); file.transferto (localfile); }} // Записать время после загрузки файла int finaltime = (int) System.currentTimeMillis (); System.out.println (finaltime - pre); }} return "/успех"; } @RequestMapping ("/toupload") public String toupload () {return "/upload"; }} 6. Наконец, посмотрите на данные о фоновой печати. Данные поступают от времени, которое необходимо для загрузки файлов, напечатанных в фоновом режиме. Первое изображение - это время, необходимое для загрузки каждого файла в три файла, используя Byte Stream. Второе изображение - это время, необходимое для загрузки каждого файла в три идентичных файла, используя анализатор, завернутый в Springmvc:
Byte Stream реализует эффективность доставки загрузки файлов, и результаты показывают, что время, необходимое для передачи трех файлов, составляет 534 мс, 453 мс и 387 мс соответственно.
Время загрузки файлов с использованием анализатора SpringMVC составляет 2 мс, 1 мс и 2 мс соответственно.
Сравнивая эти два метода, мы можем обнаружить, что использование SpringMVC для нескольких файлов, очевидно, гораздо более эффективно, чем написание символов.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.