먼저 주소 http://fex-team.github.io/webuploader/를 버립니다.
비교적 완전한 데모 케이스 문서가 있습니다. 이 기사는 주로 파일 업로드 및 이미지 업로드를 기반으로 많은 수의 댓글을 추가하여 기본적으로 각 코드 줄에 이해하는 데 도움이되는 주석이 있는지 확인합니다. 공식 웹 사이트 데모의 향상된 버전입니다. 모든 사람이 플러그인을 더 잘 이해하는 데 도움이되기를 바랍니다.
먼저 파일 업로드
jQuery (function () {var $ = jQuery, $ list = $ ( '#thelist'), $ btn = $ ( '#ctlbtn'), state = 'pending', uploader; // 초기화, 실제로 webuploader.uploader Uploader = webuploader.create ({// uncompressed resize : // // // + '/js/uploader.swf', // 서버 서버에 저장하는 배경 코드로 보내십시오 업 로더는 큐에 큐에 추가되면 업 로더를 추가 할 때 ( 'filequeued', function (file) {// 큐에 합류 할 때 후속 업로드를 실패하는 등의 스타일을 정의합니다. '<p> 업로드 대기 ... </p>' + '</div>'; // $ li에서 클래스 진행 상황을 찾아 $ %로 정의하십시오 ----- '</div>'. 성공적으로 업로더 업 로더 ( '업로드 소스', 함수 (파일) {// 파일이 추가 될 때 트리거되고 텍스트를 $ ( '#'+file.id) .find ( 'p.state')로 추가합니다. 텍스트 ( '업로드'); 'uploaderror', function (file) {// 파일이 추가 될 때 트리거되고, 찾기 시작하고, 텍스트를 업로드 오류 ( '#'+file.id) .find ( 'p.state')로 추가합니다. ) {// 전화 ( '#'+file.id) .find ( '. Progress'); // 모든 트리거는 유형의 기능이 현재 트리거되고 값을 부여하는 것입니다. else === 'stopupload') {state = 'uploadfinished') {state 텍스트 팝업 (state === upload) {$ btnex}); 버튼이 클릭되면 상태에 따라 업로드가 시작되거나 $ btn.on ( 'click', function () {if (state === 'upload') {uploader.stop ();} else {uploader.upload ();});그런 다음 사진을 업로드하십시오
jQuery (function () {// jQuery를 전역 변수 var var $ = jQuery, $ list = $ ( '#filleList'), // Retina, Retina에서 최적화,이 값은 2, 장치 픽셀 비율 비율 = Window.devicePixelratio || 1, // 썸네일 크기, // Wammberio, Wammberio, Wammberio, Wammberio, // 업 로더 인스턴스 업로더; // 웹 업 로더 업 로더 초기화 = webuploader.create ({// 자동 업로드. Auto : // SWF 파일 경로 SWF : BASE_URL + '/JS/UPLOADER.swf', // 서버를 호출하고 서버에서 이미지를 저장합니다. 'http://webuploader.duapp.com/server/fileupload.php', // 현재 실행에 따라 내부적으로 생성. 'gif, jpg, jpeg, bmp, png', mimetypes : 'image/*'});이 이벤트는 파일이 업로더를 추가 할 때 트리거됩니다. info '<div>' + file.name + '</div>' + '</div>'), $ img = $ li.Find ( 'IMG'); // 콜백에는 오류가 호출되면 SRC는 썸네일 업 로더의 주소를 저장합니다. });//파일 업로드 중에 실시간으로 표시 할 진행률 표시 줄을 만듭니다. .pindto ( 'span') ) .addclass ( '업로드 상태'); // 업로드가 실패했습니다. $ (<div> </div> '). $ li).아래는 업로드 된 파일을 얻고 업로드 된 파일의 실제 경로를 서버에 작성하는 데 사용되는 Java 배경 코드입니다.
1. 우선, 업로드 된 파일의 스토리지 위치를 작성해야합니다. 일반 위치는 임시 및 실제 폴더로 나뉩니다. 그런 다음이 두 폴더의 절대 경로를 얻어야합니다. 서블릿에서 우리는 이것을 할 수 있습니다.
ServletContext Application = this.getServletContext (); 문자열 tempdirectory = application.getRealPath (constant.temp_directory) + "/"; 문자열 realDirectory = application.getRealPath (constant.real_directory) + "/";
그런 다음 파일 공장, 즉 창고, 매개 변수는 플러시를 저장하는 것이 얼마나 큰지를 나타냅니다.
코드 사본은 다음과 같습니다. FileItemFactory Factory = New DiskFileItemFactory (constant.size_threshold, 새 파일 (tempDirectory));
ServletFileUpload 업로드 = 새로운 ServletFileUpload (공장);
2. 업로드 된 파일을 설정하십시오
upload.setsizemax (500*1024*1024); //이 업로드의 최대 값을 500m3까지 최대 500m3까지 설정하고 요청 본문을 구문 분석하고 업로드 파일을 가져오고 예외를 던지지 않고 실제 경로를 작성하십시오.
목록 <fileItem> list = upload.parserequest (요청); iterator <fileitem> iter = list.iterator (); while (iter.hasnext ()) {fileitem item = iter.next (); //item.isformfield ()는 현재 객체가 파일 양식 필드의 데이터인지 확인하는 데 사용됩니다. 반환 값이 true 인 경우 (item.isformfield ()) {system.out.println ( "일반 양식 필드" +item.getfieldName ()); System.out.println (item.getString ( "UTF-8")); } else {//system.out.println("file form field " + item.getfieldName ()); /** 파일 양식 필드만이 객체의 내용을 실제 폴더에 씁니다*/String lastPath = item.getName (); // 업로드 된 파일의 이름을 가져옵니다. lastPath = lastPath.SubString (lastPath.LastIndexOf ( ".")); 문자열 filename = uuid.randomuuid (). tostring (). replace ( "-", "") + lastpath; item.write (새 파일 (RealDirectory+filename)); package com.lanyou.support.servlet; import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.list; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; 가져 오기 javax.servlet.http.httpervletrequest; import javax.servlet.http.htttp.httpervletresponse; import net.sf.json.jsonobject; import org.apache.commons.fileuplead.fileitem; import org.apache.commons.fileupload.file -import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; commons.commons org.apache.struts2.ServletActionContext; public class fileUpload는 httpservlet {private static final long serialversionuid = 1L; private static logger = logfactory.getLog (fileUpload.class); @override protected void doget (httpservletrequest req, httpservletresponse resp) servletexception, ioexception {dopost (req, resp); } @override Protected Void Dopost (httpservletrequest req, httpservletrepsonse resp) servletexception, ioexception {// 파일 업로드 이벤트 2apk 문자열 t = req.getParameter ( "t") == null? "1": req.getParameter ( "t") .trim (); 문자열 경로 = ""; jsonobject ob = new jsonobject (); {// 작업 요청 메시지의 각 항목을 별도의 디스크 파일 템 객체로 캡슐화하려는 작업을 시도하십시오. // 업로드 된 파일 항목이 작을 때 메모리에 저장하고 디스크가 0 일 때 디스크에 저장하십시오 .// 파일 창고 (Factory) FileItemFactory factory = new DiskFileItemFactory (); servletfileupload servletfileupload = 새로운 servletfileupload (공장); // 업로드 된 파일 설정 ServletFileUpload.setSizemax (1024 * 1024 * 2); // 최대 2m Data ServletFileUpload.setfilesizemax (2 * 1024 * 1024); servletfileupload.setheaderencoding ( "utf-8"); // breadbled 파일 이름의 문제 해결 // 요청 본문을 해결하고, 업로드 된 파일을 가져오고, 업로드 된 파일을 가져오고, 예외가 발생하지 않으면 실제 경로를 작성하십시오. // 파일 목록에서 별도의 파일 객체를 가져옵니다 (fileItem item : fileItemsList) {// 파일이 일반 양식 유형인지 결정합니다. 여기서 파일 유형이 판단을 입력하는 경우 (! item.isformfield ()) {// 업로드 된 파일이 지정된 크기보다 크면 (item.getsize ()> 1024 * 1024) {return; } // system.out.println ( "업로드 된 파일의 크기 :"+item.getSize ()); // system.out.println ( "파일 유형 업로드 :"+item.getContentType ()); // system.out.println ( "파일 이름 업로드 :"+item.getName ()); // 파일 업로드 이름 문자열 filename = item.getName (); 문자열 ent = ""; // 컨텐츠 유형 if (item.getContentType (). equalSignoreCase ( "image/x-png") || item.getContentType (). equalSignoreCase ( "image/png")) {ent = ".png"; } else if (item.getContentType (). equalSignoreCase ( "image/gif")) {ent = ".gif"; } else if (item.getContentType (). equalSignoreCase ( "image/bmp")) {ent = ".bmp"; } else if (item.getContentType (). equalSignoreCase ( "image/pjpeg") || item.getContentType (). equalSignoreCase ( "image/jpeg")) {ent = ".jpg"; } // if (filename.lastIndexof ( ".")! = -1) {ent = filename.substring (filename.lastIndexof ( ".")); } filename = "ev_" + System.CurrentTimeMillis () + ENT; // 폴더 구조에 따라 파일 경로를 정의하면 (t.equals ( "1")) {path = "upload/ev/" + filename; } else {path = "upload/pk/" + filename; } // 파일을 서버 파일에 저장 파일 = 새 파일 (req.getSession (). getServletContext () .getRealPath (path)); if (! file.getParentFile (). } item.write (파일); // logger.info (경로); // 부서지다; ob.accumulate ( "url", Path); }} resp.setContentType ( "text/html; charset = utf-8"); resp.getwriter (). 쓰기 (ob.toString ()); } catch (예외 e) {e.printstacktrace (); } 마침내 {// 응답 클라이언트 // resp.setContentType ( "text/html; charset = utf-8"); // resp.getWriter (). 쓰기 (ob.toString ()); }}}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.