Existem duas maneiras de implementar o upload de vários arquivos no SpringMVC. Um é fazer upload de arquivos em um fluxo de bytes que costumamos usar, e o outro é carregá -los usando um analisador embrulhado no SpringMVC. Esses dois métodos têm uma grande lacuna na eficiência de obter upload de vários arquivos. Vamos dar uma olhada nos métodos de implementação desses dois métodos por meio de exemplos e comparar o tamanho da lacuna na eficiência.
1. Faça o download do pacote JAR relevante. In addition to the jar package of springMVC, com.springsource.org.apache.commons.fileupload-1.2.0.jar and com.springsource.org.apache.commons.io-1.4.0.jar and com.springsource.org.apache.commons.io-1.4.0.jar are also needed.
2. Configure o arquivo Springannotation-ervlet.xml (o nome do arquivo pode ser personalizado, desde que seja o mesmo que o nome introduzido em web.xml):
<?xml version="1.0" encoding="UTF-8"?> <!-- Bean header--> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" 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/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 "> <!-ANOTAÇÃO PACOTO-> <Contexto: Componente-Scan Base-Package = "com.tgb.web.controller.annotation"> </context: component-scan> <!-Substitua as duas linhas a seguir de código-> <mvc: anotação-driven/> <!-Access de recursos estáticos-> <mvc: recursos de recursos = "/iMg/" location = "/img/* maping = "/js/**"/> <bean id = "viewResolver"> <propriedade name = "prefixo" value = "/"> </propriedade> <propriedade name = "sufix" value = ". name = "maxuploadSize" value = "10485760000"> </property> <propriedade name = "maxinMemorySize" value = "40960"> </propriedade> </bean> </ Beans>
3. Configure o arquivo 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.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" = "2.5">>> <lmed-File> index.html </ld-Welcome-file> </ld-Welcome-File-List> <Vertlet> <Verlet-Name> Springmvc </Servlet-Name> <!-Springmvc Distributor-> ParammatLass </ServletLast-cllass-cxtSotSl/InitterLatSl/InitterLatsl. <amam-value> ClassPath*: config/springannotation-ervlet.xml </param-value> </init-param> <!-indica que o servlet é inicializado quando o tomcat é iniciado-> <lound-on-startup> 1 </arload-on-startup> </servlet> <ftrotle> <filtroname> ° <Filter-Class> org.springframework.web.filter.characterencodingFilter </filter-Class> <iit-param> <amam-name> Encoding </amam-Name> <amam-value> utf-8 </param-value> <!-Defina o conjunto de caracteres que deseja usar. I am using GB18030--> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> <!--Set the page or servlet you want to filter, Configure-o de acordo com suas necessidades-> </filter-mapping> <Servlet-Mapping> <Verlet-Name> Springmvc </Servlet-Name> <rict-pantathern>/</url-pattern> </servlet-mapping> </web-app>
4. Código da página JSP:
<%@ página linguagem = "java" contentType = "text/html; charset = utf-8" PageEncoding = "utf-8"%> <! <html> <head> <script type = "text/javascript" src = "../ js/jQuery-1.7.2.js"> </sCript> <meta http-equiv = "content-ttype" content = "text/html; charset = utf-8"> <tittle> insert "title j = 1; $(document).ready(function(){ $("#btn_add1").click(function(){ document.getElementById("newUpload1").innerHTML+='<div id="div_'+i+'"><input name="file" type="file" /><input type="button" value="Delete" ONCLICK = "Del_1 ('I+')"/> </div> '; /> <input Type = "Button" Value = "excluir" OnClick = "Del_2 ('+J+')"/> </div> '; function del_1 (o) {document.getElementById ("newupload1"). removechild (document.getElementById ("div _"+o)); } função del_2 (o) {document.getElementById ("newupload2"). removechild (document.getElementById ("div _"+o)); } </script> </ad Head> <body> <h1> springmvc byte fluxo de entrada Arquivo de upload </h1> <name = "userForm1" action = "/springmvc7/file/upload" ENCTYPE = "multipart/form-data" Método = "post"> <divd = "newUplOad1"> <nput/input "type =" file "> <Div =" newUPLOD) <nput/input/input ") id = "btn_add1" value = "Adicione uma linha"> <input type = "submit" value = "upload"> </morm> <br> <hr align = "left" color = "#ff0000" size = "3"> <br> <h1> springmvc wrapper File upload </h1> <form> " enctype="multipart/form-data" method="post""> <div id="newUpload2"> <input type="file" name="file"> </div> <input type="button" id="btn_add2" value="add one line"> <input type="submit" value="upload" > </form> </body> </html>5. Java Bean que implementa a função de upload:
pacote com.tgb.web.controller.annotation.upload; importar java.io.file; importar java.io.fileInputStream; importar java.io.fileOutputStream; importar java.io.ioException; importar java.io.printwriter; importar java.io.unsupportEnCodingException; importar java.net.urldecoder; importar java.util.date; importar java.util.iterator; importar javax.servlet.http.httpServletRequest; importar javax.servlet.http.httpServletResponse; importar javax.swing.FileChooser.FileNameExtensionFilter; importar org.springframework.tereotype.controller; importar org.springframework.web.bind.annotation.requestmapping; importar org.springframework.web.bind.annotation.requestmethod; importar org.springframework.web.bind.annotation.requestparam; importar org.springframework.web.multipart.multipartFile; importar org.springframework.web.multipart.multiparthttpServletRequest; importar org.springframework.web.multipart.commons.commonsmultipartFile; importar org.springframework.web.multipart.commons.commonsmultipartresolver; importar org.springframework.web.servlet.modelandView; importar com.tgb.web.controller.entity.user; @Controller @RequestMapping ("/FILE") Classe public UPLOPLONTROLLER {@ReQuestMapping ("/upload") public String adduser (@RequestParam ("arquivo") commonsmultipartFile [] arquivos, i (iSttPerVleTrequest request) {for (int i = 0; System.out.println ("nome do arquivo --------->" + arquivos [i] .getoriginalfilename ()); if (! arquivos [i] .isempty ()) {int pre = (int) System.currenttimemillis (); tente {// Obtenha o fluxo de saída e renomeie o arquivo fileout FileOutputStream OS = new FileOutputStream ("H:/" + new Data (). gettime () + arquivos [i] .getoriginalFilename ()); // Obtenha o fluxo de entrada do arquivo FileInputStream do FileInputStream em = (FileInputStream) [i] .getInputStream (); // Escreva o arquivo int b = 0; while ((b = in.read ())! = -1) {os.write (b); } os.flush (); os.close (); in.Close (); int final time = (int) System.currenttimemillis (); System.out.println (finaltime - pre); } catch (Exceção e) {e.printStackTrace (); System.out.println ("UPLOPLEERROR"); }}} retornar "/sucesso"; } @RequestMapping ("/upload2") public string upload2 (solicitação httpServletRequest, httpServletResponse resposta) lança ilegalStateException, ioexception {// crie comnsmultiParTriSolver CommOnsmultiPARTRESOLVERSOLVERSOLVER =. // Defenda se a solicitação possui upload de arquivo, ou seja, se (multipartresolver.ismultipart (request)) {// converter para múltipla solicitação multiparthttpServletRequest multirequest = (multiparthttpServletRequest) solicitação; // Obtenha todos os nomes de arquivos no iterador de solicitação <String> iter = multIREQUEST.getFilenames (); while (iter.hasnext ()) {// grava o tempo no início do processo de upload e use -o para calcular o tempo de upload int pre = (int) System.currenttimemillis (); // Obtenha o arquivo de upload multipart arquivo = multirequest.getFile (iter.Next ()); if (arquivo! // Se o nome não for "", significa que o arquivo existe, caso contrário, significa que o arquivo não existe se (myFileName.trim ())! = "") {System.out.println (myFileName); // renomear o nome do arquivo carregado string filename = "Demoupload" + file.getoriginalfilename (); // Defina o caminho de upload Path String Path = "H:/" + FileName; Arquivo localfile = novo arquivo (caminho); file.Transferto (LocalFile); }} // Registre o tempo após o upload do arquivo int finalTime = (int) System.currenttimemillis (); System.out.println (finaltime - pre); }} retornar "/sucesso"; } @RequestMapping ("/TOUPLOAD") public String TouPload () {return "/upload"; }} 6. Finalmente, observe os dados de impressão em segundo plano. Os dados vêm do tempo necessário para fazer upload de arquivos impressos em segundo plano. A primeira foto é o tempo que leva para fazer upload de cada arquivo em três arquivos usando gravação de bytes. A segunda foto é o tempo que leva para fazer upload de cada arquivo em três arquivos idênticos usando um analisador embrulhado no springmvc:
O fluxo de bytes realiza a eficiência da entrega do upload de arquivo e os resultados mostram que o tempo necessário para passar os três arquivos é de 534ms, 453ms e 387ms, respectivamente.
O tempo para fazer upload de arquivos usando o analisador Springmvc é de 2ms, 1ms e 2ms, respectivamente.
Ao comparar esses dois métodos, podemos descobrir que o uso do SpringMVC para vários arquivos é obviamente muito mais eficiente do que escrever caracteres.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.