코드 만보세요. 주석이 모두 안에 있습니다.
우선, web.xml
<? xml version = "1.0"encoding = "utf-8"?> <web-app version = "2.5"xmlns = "http://java.sun.com/xml/xml/ns/javaee"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance. xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd. <Servlet-Class> org.springframework.web.servlet.dispatcherServlet </servlet-class> <init-param> <param-name> contextConfigLocation </param-name> <param-value> classpath : applicationcontext.xml </param-value> </init-param> </servitup> 1 </startup> 1 </startup> 1 <SERVLET-MAPPEND> <SERVLET-NAME> 업로드 </servlet-name> <Url-Pattern>/</url-pattern> </servlet-mapping> <filter> <description> 매개 변수 전달에서 garbled 문제 해결 </description> <filter-name> char <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> incoding </param-name> <param-value> utf-8 </param- value> </init-param> </init-param> </filter-mapping> </relterf8 </relterf8 <Url-pattern>/*</url-pattern> </필터 매핑> </web-app>
아래는 //src//applicationcontext.xml에 있습니다
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : mvc = "http://www.springframework.org/schema/mvc"xmlns : context = "http://www.springframework.org/schema/context"xsi : skemalocation = "http://www.spremframframwork.org/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/sprging-mvc-3.xsd http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/context/spring-context-3.2.xsd ">-Spring Spring의 자동 스캐닝 (Spring 's Spare Scan 및 Subpackates). BASE-PACKAGE)-> <!-여기에서 내 기사 http://blog.csdn.net/jadyer/article/details/6038604-> <context : component-scan base-package = "com.jadyer"/> <!-SpringMVC Innotation Function, Alorthorically Registern Instances of HandlerMapping, HandlerTor 및 관련 인스턴스를 참조하십시오. -> <MVC : Annotation-Driven/<!-SpringMVC가 Web.xml에서 모든 요청을 가로 채기 위해 설정되어 있으므로 정적 리소스 파일을 읽을 때 읽지 않습니다.-> <!-이 구성을 통해 "/js/"에서 찾을 수있는 모든 리소스를 지정할 수 있으며 "/js/"에서 찾을 수 있습니다. location = "/js/"/> <mvc : 리소스 매핑 = "/upload/** 위치 ="/upload/"/> <!-SpringMVC에서 파일을 업로드 할 때 멀티 펀드 러 솔버 프로세서-> <bean id ="multipartresolver "> <!-업로드 된 파일의 총 크기를 초과 할 수 없음을 지정해야합니다. 단일 파일의 경우가 아니라 모든 파일의 용량의 합계-> <속성 이름 = "maxuploadsize"value = "800000"/> </bean> <!-SpringMVC가 업로드 파일 제한을 초과하면 org.springframework.web.multipart.multipart.multipart.multipartizeexception을 던질 것입니다. 그리고 현재 컨트롤러 메소드를 입력하지 않았습니다-> <bean id = "ExceptionResolver"> <property name = "ExceptionMappings"> <props> <! ~-maxUploadSizeexexexception 예외를 만나면 /web-inf/jsp/error_fileupload.jsp-> <prop로 자동 이동합니다. key = "org.springframework.web.multipart.maxuploadsizeexexexception"> error_fileupload </props> </property> </bean> <bean> <property name = "prefix"value = "/web-inf/jsp/"/> <property name = "valud ="</bean> </bean> </bean> </bean>.
다음은 파일 콘텐츠를 업로드하는 것이 너무 큰 //web-inf//jsp//error_fileupload.jsp가 될 때의 프롬프트 페이지입니다.
<%@ page language = "java"pageencoding = "utf-8"%>
<H1> 파일이 너무 큽니다. Reselect </h1>
아래는 파일 index.jsp를 선택하기위한 업로드 페이지입니다
<%@ page language = "java"pageencoding = "utf-8"%> <!-이것은 <script type = "text/javaScript"src = ".."// js/jquery-1.10.2.min.js "> </script> <script> <script> javascript"로 축약 할 수 없습니다. src = "<%= request.getContextPath ()%>/js/ajaxfileupload.js"> </script> <script type = "text/javaScript"src = "<%= request.getContextPath ()%>/js/ajaxfileupload.js"> ajaxfileupload () {// 파일을 업로드 할 때 그림이 표시되고 파일 업로드가 사진을 숨기려고 완료됩니다. // $ ( "#loading"). // 파일 업로드 작업의 서버 주소 (매개 변수는 전달 될 수 있으며 개인적으로 테스트되었습니다) URL : '$ {pagecontext.request.contextPath}/test/fileUpload? uname = Xuanyu', SecureUri : false, // Secure Commit이 활성화되어 있는지, 기본적으로 falseElementId : 'myBlogimage : // whblogipe' // 서버에서 반환 한 형식은 JSON 또는 XML 등이 될 수 있습니다. 성공 : 함수 (데이터, 상태) {// 처리 함수 데이터 = data.Replace ( "<fre>", ''); // ajaxfileupload는 서버가 다시 응답하는 텍스트 내용에 <fre> text </pre>의 접미사를 추가합니다. data = data.replace ( "</pre>", ''); data = data.replace ( "<fre>", ''); data = data.replace ( "</pre>", ''); data = data.replace ( "</pre>", ''); //이 예에서 업로드 파일이 완료된 후 서버는 전경으로 돌아갑니다. Data.Substring (2)); $ ( '#result'). html ( "이미지 업로드가 성공적으로 <br/>"); } else {$ ( '#result'). html ( '이미지 업로드 실패, 다시 시도하십시오!'); }}, error : 함수 (data, status, e) {// 처리 함수 $ ( '#result'). html ( '이미지 업로드 실패, 다시 시도하십시오 !!'); }});}} </script> <div id = "result"> </div> <img id = "uploadImage"src = "http://www.firefox.com.cn/favicon.ico"> <입력 유형 = "id ="myblogimage "name ="myfiles ""value = ""upload " onclick = "ajaxfileupload ()"/> <!-ajaxfileupload 공식 웹 사이트 소개 : http://phpletter.com/our-projects/ajaxfileupload/introduction : jquery plug-in ajaxfileupload는 새로 고침 무료 업로드 파일을 달성 할 수 있으며 간단하고 사용하기 쉽습니다. 사용자가 많습니다. 권장 할 가치가 있습니다 : JS (jQuery에 따라 다름)의 순서는 페이지에 양식이 없습니다 (버튼을 클릭 할 때 AjaxFileUpload () 메소드를 트리거) 일반 오류 및 솔루션은 다음과 같습니다. 1) SyntaxError : 누락; 명령문 -URL 경로에 액세스 할 수 있는지 확인합니다. 위의 유효하지 않은 오류 프롬프트보다 훨씬 편리한 변수 $ 오류 -> 마지막으로 파일 업로드를 처리하는 FileUploadController.java
package com.jadyer.controller; import java.io.file; import java.io.ioexception; import java.io.printwriter; import javax.servlet.htttp.htttp.htttp.htttp.httpervletrequest; import javax.servlet.http.http.httpervletresponse; import org.apache.commons.fileutils; org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.requestmapping; import org.sprameframework.beb.bind.annotation.requestparam; import org.spramework.web.multipartfile;/* uppart.multipartfile; SpringMVC는 Commons-FileUpload 구현을 사용합니다. 먼저 구성 요소를 프로젝트에 소개해야합니다 * 2) SpringMVC 구성 파일에서 Multipartresolver 프로세서 구성 (업로드 된 파일의 속성 제한은 여기서 추가 될 수 있음) * 3) 컨트롤러 방법에 MultipartFile 매개 변수를 추가로 추가로 작성하는 데 사용되었습니다. * 4). ENCTYPE = "multipart/form-data"및 <input type = "file"name = "****"/>)*ps : ps : ajaxfileupload.js는 새로 고침없는 업로드를 달성하는 데 사용 되므로이 예에서는 양식이 사용되지 않습니다* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Spring-Context-3.2.4.Release.jar * Spring-Core-3.2.4. Release.jar * Spring-Expression-3.4. Release.jar * Spring-jdbc-3.4. Release.jar * Spring-Oxm-3.2.4.release.jar * spring-tx-3.2.4. Release.jar.release.jar.release.release.jar * spring-web-2.4.2. Spring-Web-3.2.4. Release.jar * Spring-Webmvc-3.2.4. Release.jar * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 파일을 업로드 한 후 전경으로 돌아온 후 [0`FilePath], 0은 성공적으로 업로드하는 (업로드 된 파일 경로에 시퀀스)를 의미합니다 (실패 설명에 시퀀스) */ @requestmapping (value = "/ fileUpload") public String Adduser (@requestparam ( "Uname") String Uname, @RtpiTERAM [] MyFILES, MYFILES, @RTPERSORM request, httpservletresponse responsk)는 ioexception을 던지려면 {// 파일 시스템을 업로드하는 동안 다른 매개 변수를받을 수 있습니다. // Tomcat 서버를 사용하는 경우 파일이 //%tomcat_home%// webapps // yourwebproject // 폴더 // commons.io.fileutils 클래스에 업로드 작업을 구현하는 데 사용됩니다. 자동으로 /업로드가 있는지 확인합니다. 존재하지 않으면 string realpath = requestsession (). getServletContext (). getRealPath ( "/upload"); // 전경 컨텐츠 응답에 대한 데이터 형식 응답을 설정합니다 .SetContentType ( "Text/Plain; charset = utf-8"); // 전경 컨텐츠에 응답하는 인쇄기 객체를 설정합니다. printwriter out = response.getWriter (); // 업로드 파일의 원래 이름 (즉, 업로드하기 전에 파일 이름) 문자열 ordinkfilename = null; // 하나의 파일을 업로드하면 파일을 multipartFile 유형으로 만 수신하기 만하면 @RequestParam 주석을 명시 적으로 지정할 필요가 없습니다. // 여러 파일을 업로드하려면 MultipartFile을 사용하여 파일을 수신하기 위해 유형을 사용해야합니다. MyFiles, 그렇지 않으면 매개 변수의 MyFiles는 (MultiptartFile MyFile : MyFiles) {if (myfile.isempty ()) {out.print ( "1 '파일을 선택하고 업로드하는")에 대해 업로드 된 모든 파일을 얻을 수 없습니다. out.flush (); 널 리턴; } else {OriginalFileName = myFile.getoriginalFilename (); System.out.println ( "파일 원본 이름 :" + OriginalFilename); System.out.println ( "파일 이름 :" + myfile.getName ()); System.out.println ( "파일 길이 :" + myfile.getSize ()); System.out.println ( "파일 유형 :" + myfile.getContentType ()); System.out.println ( "==================================================================================================================== System.out.println ( "=========================================================================================================== ======================================================================================================= ======================================================================================================= ====================================================================================================== {System.out.println ( " + OriginalFilename +"는 스택 트랙이 실패했습니다 [d : /develoy/apache-tomcat-6.0.36/webapps/ajaxfileupload//upload/anger birds.jpg] //system.out.println(RealPath + "//" + OriginalFilename. //system.out.println (request.getContextPath () + "/upload/" + OriginalFilename); // [realPath + "//" + OriginalFilename]의 권장 사항은 <img src = "파일 : /// d : /aa.jpg">가 Windows에서 Firefox에서 표시 할 수 있기 때문에 권장되지 않습니다. OriginalFilename); out.flush (); 널 리턴; }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.