SpringMVC에서 멀티 파일 업로드를 구현하는 두 가지 방법이 있습니다. 하나는 우리가 자주 사용하는 바이트 스트림에 파일을 업로드하는 것이고, 다른 하나는 파일을 SpringMVC로 랩핑 한 파서를 사용하여 파일을 업로드하는 것입니다. 이 두 가지 방법은 멀티 파일 업로드를 달성하는 효율성에 큰 차이가 있습니다. 예제를 통해이 두 가지 방법의 구현 방법을 살펴보고 효율의 격차가 얼마나 큰지 비교해 봅시다.
1. 관련 JAR 패키지를 다운로드하십시오. SpringMVC의 JAR 패키지 외에도 com.springsource.org.apache.commons.fileupload-1.2.0.jar 및 com.springsource.org.apache.commons.io-1.4.0.jar 및 com.springsource.org.apache.comson.oi-4.0.jar도 필요합니다.
2. SpringAnnotation-servlet.xml 파일 구성 (Web.xml에 소개 된 이름과 동일하다면 파일 이름을 사용자 정의 할 수 있습니다) :
<? xml version = "1.0"encoding = "utf-8"?> <! <!-bean 헤더-> <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.springframwork.org/schema/SCEMA xmlns : util = "http://www.springframework.org/schema/util"xsi : schemalocation = "http://www.springframework.org/schema/beans http://ww.springframework.org/schema/beans/spred-beans- 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 "> <!-주석 스캔 패키지-> <context : component-scan 기본-패키지 = "com.tgb.web.controller.annotation"> </context : comperent-scan> <!-다음 두 줄의 코드를 교체-> <mvc : static resource access-> <mvc : resources location = "/img/"mapping = "/img/** <mvc : Resources 위치 :"/js/" 맵핑 = "/js/**"/> <bean id = "viewResolver"> <속성 이름 = "prefix"value = "/"> </property> <속성 이름 = "접미어"value = ". jsp"> </bean> <bean id = "multipartresolver"> <property name = "value ="valloding ""max < "max" value = "10485760000"> </property> <속성 이름 = "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"> <display-name> springmvc1 </display-name> <환영 파일> index.html </welcome-file> </welcome-file-list> <servlet> <servlet-name> springmvc </servlet-name> <!-springmvc distributor-> <servlet-class.springframework.web.servlet.dispatcherservlet </servletclass </servlet class> <param- value> classpath*: config/springAnnotation-servlet.xml </param-value> </init-param> <!-tomcat이 시작될 때 서플릿이 초기화되었음을 나타냅니다-> <load-on-startup> 1 </load-on-startup> </servlet> <filter-name> encodingfilter </filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> incoding </param-name> <param-value> utf-8 </param- value> <!-사용하려는 문자를 설정하십시오. 나는 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> <! 필터를 필터링하고 필요에 따라 구성하려고합니다 .-> </필터 맵핑> <Servlet-Mapping> <Servlet-Name> SpringMVC </servlet-name> <Url-Pattern>/</url-pattern> </servlet-mapping> </web-app>
4. JSP 페이지 코드 :
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 transitional // en" "http://www.w3.org/tr/tml/html 4/tml/html 4/tml 4.html/html 4.tml. <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 "> <title> 여기에 제목 </title> <text/javascript"; j = 1; $ (document) {function () {$ ( "#btn_add1"). 클릭 (function () {document.getElementByid ( "newUpload1"). innerHtml+= '<div id = "div _'+i+'"> <입력 이름 = "file"file " /> <입력 유형 ="values = "delete" onclick = "del_1 ( '+i+')"/> </div> '; "#btn_add2"). /> < "value ="delete "onclick ="del_2 ( '+j+') "; 함수 del_1 (o) {document.getElementById ( "newUpload1"). removeChild (document.getElementById ( "div _"+o)); } function del_2 (o) {document.getElementById ( "newUpload2"). removeChild (document.getElementById ( "div _"+o)); }. id = "btn_add1"value = "한 줄 추가"> <입력 유형 = "value ="upload "> </form> <br> <hr align ="left "color ="#ff0000 "size ="3 "> <br> <h1> springmvc 래퍼 클래스 업로드 파일 </h1> <user name ="userform2 "acture ="/springmvc7/file/upload " EncType = "multipart/form-data"method = "post" "> <div id ="newUpload2 "> <input type ="file "name ="file "> </div> <input type ="id = "btn_add2"value = "input type ="value = "upload"> </html> </html> </html> </html> </html> </html> </html>5. 업로드 기능을 구현하는 Java Bean :
package com.tgb.web.controller.annotation.upload; import java.io.file; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.ioexception; import java.io.printwriter; java.io.unsupportedencodingException 가져 오기; import java.net.urldecoder; import java.util.date; import java.util.iterator; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.swing.filechooser.filenameextensionFilter; org.springframework.stereotyp.controller import; 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; org.springframework.web.multipart.commons.commonsmultipartfile; org.springframework.web.multipart.commons.commonsmultipartresolver; org.springframework.web.servlet.modelandview import; import com.tgb.web.controller.entity.user; @controller @requestmapping ( "/file") public class uploadcontroller {@requestmapping ( "/upload") public string adduser (@requestparam ( "file") commonsmultipartfile [] 파일, httpservletrequest request) {or (int i = 0; i <files.length; i ++) { System.out.println ( "filename ---------->" + 파일 [i] .getoriginalFilename ()); if (! files [i] .isempty ()) {int pre = (int) system.currentTimeMillis (); {// 출력 스트림을 가져 와서 업로드 된 파일 파일의 이름을 바꾸십시오. 파일 아웃 PutStream os = new FileOutputStream ( "h :/" + new Date (). getTime () + 파일 [i] .getoriginalFilename ()); // 업로드 된 파일의 입력 스트림을 가져옵니다. fileInputStream in = (fileInputStream) 파일 [i] .getInputStream (); // int b = 0 파일을 작성합니다. while ((b = in.read ())! = -1) {os.write (b); } os.flush (); os.close (); 넣다(); int final time = (int) system.currenttimeMillis (); System.out.println (FinalTime -Pre); } catch (예외 e) {e.printstacktrace (); System.out.println ( "uploaderror"); }}} return "/success"; } @requestmapping ( "/upload2") public string upload2 (httpservletrequest request, httpservletresponse 응답)는 불법 스테이트 exception, ioexception {// 일반적인 멀티 펠트 리졸버 multipartresolver = new Commontipartresolver (). // 요청에 파일 업로드가 있는지, 즉 if (multipartresolver.ismultipart (request)) {// multiparthtpservletRequest multirequest = (multiparthttpservletRequest) 요청; // 요청 iterator <string> iter = multirequest.getFilenames ()에서 모든 파일 이름을 가져옵니다. while (iter.hasnext ()) {// 업로드 프로세스 시작시 시간을 기록하고이를 사용하여 업로드 시간 int pre = (int) system.currenttimemillis (); // 업로드 파일을 가져옵니다. multipartFile 파일 = multirequest.getFile (iter.next ()); if (file! = null) {// 현재 업로드 된 파일의 파일 이름을 가져옵니다. string myfilename = file.getoriginalFilename (); // 이름이 ""가 아닌 경우 파일이 존재한다는 것을 의미합니다. 그렇지 않으면 (myfilename.trim ())! = "") {system.out.println (myfilename); // 업로드 된 파일 이름 이름 이름으로 이름 문자열 filename = "damoupload" + file.getoriginalFilename (); // 업로드 경로 정의 문자열 경로 = "h :/" + filename; 파일 로컬 파일 = 새 파일 (Path); file.transferto (localfile); }} // 파일을 업로드 한 후 시간을 기록 int finaltime = (int) system.currentTimeMillis (); System.out.println (FinalTime -Pre); }} return "/success"; } @requestmapping ( "/toupload") public String toupload () {return "/upload"; }} 6. 마지막으로 배경 인쇄 데이터를보십시오. 데이터는 백그라운드에서 인쇄 된 파일을 업로드하는 데 걸리는 시간부터 발생합니다. 첫 번째 그림은 바이트 스트림 쓰기를 사용하여 각 파일을 세 파일로 업로드하는 데 걸리는 시간입니다. 두 번째 그림은 SpringMVC에 랩핑 된 파서를 사용하여 각 파일을 3 개의 동일한 파일로 업로드하는 데 걸리는 시간입니다.
바이트 스트림은 파일 업로드의 전달 효율을 인식하고 결과는 세 파일을 전달하는 데 필요한 시간이 각각 534ms, 453ms 및 387ms임을 보여줍니다.
SpringMVC 파서를 사용하여 파일을 업로드 할 시간은 각각 2ms, 1ms 및 2ms입니다.
이 두 가지 방법을 비교하면 여러 파일에 SpringMVC를 사용하는 것이 문자 작성보다 훨씬 효율적이라는 것을 알 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.