이 기사의 예는 참조 용 Java 파일 업로드 기술을 공유합니다. 특정 내용은 다음과 같습니다
형태:
클라이언트는 HTTP를 보낼 때 복합 데이터 유형을 나타 내기 위해 멀티 파트/양식 데이터 유형을 사용해야합니다. 지금 바로:
양식에서 HTML 태그를 사용하십시오.
필수 패키지 :
Commons-FileUpload.jar, 코어 업로드 파일 도구는이 패키지에 있습니다.
파일을 업로드하는 데 필요한 Commons-IO.jar 패키지
파일 클래스 업로드에 대한 자세한 설명 :
DiskFileItemFactory- 캐시 영역 크기를 나타내는 시간 모니터링 파일 디렉토리 생성
ServletfileUpload는 httpservletrequest를 구문 분석하는 데 사용됩니다. 파일 객체 세트를 반환합니다.
FileItem은 사용자가 업로드 한 각 파일 객체를 나타냅니다.
<%@ page language = "java"import = "java.util.*"pageEncoding = "utf-8"%> <! doctype html public "-// w3c // dtd html 4.01 전환 // 보드-기본 계층을 이해하고 </font> <!-multipart/form-data : multipart (파일뿐만 아니라 파일뿐만 아니라 부품)-> <form action = "<%= request.getContextPath ()%>/upload0"method = "enctype ="infutart/form-data "> 파일 : <input type ="file "name ="input ""input ""input ". 업로드 된 파일 이름은 중국어로 될 수 없으며, 그렇지 않으면 획득 된 파일 이름은 차별화되지만 다음 예제는이 문제를 해결할 수 있습니다.> </form> <br/> <font color = "red"size = "6"> apache 파일 업로드 도구를 사용하여 파일 업로드를 사용하여 파일 업로드를 달성하기 위해-application/x-www-form-urlencoded-> <%=/upload " 메소드 = "post"enctarpe = "multipart/form-data"> 파일 : <input type = "file"name = "file"/> <입력 유형 = "value ="upload "/</form> <font color> <font"size = "6"> 파일 업로드 2를 달성하기 위해 APACH 파일 업로드 도구를 사용하여 파일 이름을 <post> post1 (정상 Form)를 사용합니다. ENCTYPE = Application/X-www-form-urlencoded (기본값) </p> <p> post2 (파일 양식 업로드) : enctype = multipart/form-data : multipart (파일뿐만 아니라 파일도) </p> <form action = "<%= request.getContPath ()%>/upload2"post "inctype" "inctype" type = "file"name = "file"/> <!-post2 (파일 양식을 업로드)-> <br/> 파일 설명 : <입력 유형 = "text"name = "desc"/> <!-post1 (정상 양식)-> <br/> 파일 2 : <입력 유형 = "file" "file"/> <br/> 파일 설명 2 : <input type = "text"name "/>>/>/>>>>>>>>>>>> <input type ="input type = "file". -> <br/> 파일 2 : <입력 유형 = "파일"이름 = "파일"/> <br/> 파일 설명 2 : <입력 유형 = "text"name = "desc"/> <입력 유형 = "value ="업로드 "/> </form> <font color ="red "size ="6 "> 파일 업로드를 사용하여 파일 업로드를 달성하기 위해 3 (파일 삭제) <! Form) : EncType = application/x-www-form-urlencoded (기본값)-> <!-post2 (파일 양식) : enctype = multipart/form-data : multipart (파일뿐만 아니라 파일뿐만 아니라)-> <form accue = "<%= request.getContextPath ()%>/upload3"inctart/worm-data "" type = "file"name = "file"/> <!-post2 (파일 양식 업로드)-> <br/> 파일 설명 : <input type = "text"name = "desc"/> <!-post1 (일반 양식)-> <br/> <br/> 파일 2 : <input type = "file"name = "file"/> <br/> 파일 설명 2 : <입력 유형 = "텍스트" 값 = "업로드"/> </form> </body> </html>
전환 보드의 하단 층을 이해합니다
패키지 CN.hncu.servlet; import java.io.bufferedReader; import java.io.ioException; import java.io.inputStream; import java.io.inputStreamReader; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.htppervlet javax.servlet.http.htttp.httpservletrequest; import javax.servlet.http.htttp.httpervletresponse; public class upload0servlet는 httpservlet {public void dopost (httpservletrequest 요청, httpservletresponse 응답) servletexcement {inputexcement {inputexcemence {inputexcemence in = request.getInputStream (); bufferedReader br = new bufferedReader (new inputStreamReader (in)); 문자열 라인; while ((line = br.readline ())! = null) {system.out.println (line); }}}Apache 파일 업로드 도구를 사용하여 파일 업로드를 구현하십시오.
패키지 cn.hncu.servlet; import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.list; import java.util.uuid; import javax.servlet.servletexception; import javax.servlet.httplet.httpp.httpervlet; javax.servlet.http.httpervletrequest; import javax.servlet.http.htttp.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import org.apache.commons.io.fileutils; public uploadservlet httpservlet {httervletrequest 요청 httpservletResponse 응답) servletexception, ioexception {response.setContentType ( "text/html"); printwriter out = response.getwriter (); out.println ( "<! doctype html public/"-// w3c // dtd html 4.01 Transitional // en/">"); out.println ( "<html>"); out.println ( "<head> <title> a servlet </title> </head>"); out.println ( "<body>"); out.print ( "Get Get 업로드를 지원하지 않습니다. ... ..."); out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {// 서버에서 업로드 된 모든 파일에 디렉토리를 지정하십시오. System.out.println ( "Path :"+Path); 파일 dir = 새 파일 (경로); if (! dir.exists ()) {dir.mkdirs (); } // 하드 디스크 기반 공장 생성 // DiskFileItemFactory 디스크 = New DiskFileItemFactory (); // 임시 디렉토리를 설정합니다 (임시 디렉토리를 설계하는 것이 좋습니다. 그렇지 않으면 시스템 임시 디렉토리가 사용됩니다.) //disk.setRepository(new file ( "d :/a")); // 3. 데이터 작성의 버퍼 크기를 하드 디스크 디스크로 설정합니다 .SetSizetHreshold (1024*4); // 파일 이이 설정보다 큰 경우 임시 디렉토리에 임시 파일이 형성됩니다. // 임시 파일 버퍼 크기를 설정합니다. -8K 버퍼, 임시 파일 주소 diskFileItemFactory f = new DiskFileItemFactory (1024*8, 새 파일 ( "d :/a"); // 업로드 도구-구문 분석 용 객체를 만듭니다. servletfileUpload 업로드 = 새로운 servletfileupload (f); upload.setfilesizemax (1024*1024*5); // 업로드 된 최대 업로드 된 단일 파일을 5m으로 설정하십시오. // 업로드 된 파일의 최대 크기를 설정합니다. 여러 파일 인 경우 최대 8m 업로드의 여러 파일의 합입니다 .SetSizEmax (1024*1024*8); // 업로드 된 모든 파일 크기의 합을 최대 8m까지 설정하십시오. // 구문 분석 도구를 사용하여 구문 분석 {list <fileItem> list = upload.parserequest (request); for (fileItem fi : list) {system.out.println ( "파일 내용 유형 :"+fi.getContentType ()); // 파일 내용 유형 : text/plain System.out.println ( "파일 이름 :"+fi.getname ()); // 파일 이름 : c : /users/adl1/desktop/a.txt string ext = fi.getName (). substring (fi.getName (). lastIndexOf ( ".")); //. txt String uuid = uuid.randomUuid (). toString (). Replare ( "-", ""); String filename = uuid+ext; // fileUtils.copyInputStreamTofile (fi.getInputStream (), 새 파일 ( "d : /a/d/a.txt"); // write it dead // fi.getInputStream ()은 실제 파일 정보 파일입니다 .CopyInputStreamTofile (fi.getInputStream (), 새로운 파일 정보입니다. 파일 (path+"/"+filename)); // 작성}} catch (fileUploadexception e) {e.printstacktrace (); }}} 이 장소에 업로드 된 파일을 저장하십시오
정보 업로드 :
결과 업로드 :
Apache 파일 업로드 도구를 사용하여 파일 업로드 2를 달성합니다 (garbled 파일 이름 해결)
패키지 cn.hncu.servlet; import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.list; import java.util.uuid; import javax.servlet.servletexception; import javax.servlet.httplet.httpp.httpervlet; javax.servlet.http.httpervletrequest; import javax.servlet.http.htttp.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import org.apache.commons.io.fileutils; public upload2servlet httpervlet (httpervlet) (httpervletrequest restims) httpservletResponse 응답) servletexception, ioexception {response.setContentType ( "text/html"); // 업로드 된 파일 (post2)이 포함 된 양식 인 경우 드라마는 업로드 된 파일의 파일 이름으로 만 인코딩을 설정할 수 있지만 (중국의 갈색 블러 블 코드 해결) // post2 mode printwriter out = respint.getwriter ()에서 일반 양식 구성 요소의 중국어가 달린 코드를 해결할 수는 없습니다. out.println ( "<! doctype html public/"-// w3c // dtd html 4.01 Transitional // en/">"); out.println ( "<html>"); out.println ( "<head> <title> a servlet </title> </head>"); out.println ( "<body>"); out.print ( "Get Get 업로드를 지원하지 않습니다. ... ..."); out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); } public void dopost (httpservletrequest 요청, httpservletreponse response)는 servletexception, ioexception {// 일반 양식 양식 (Post1)을 던지고 다음 문장은 일반 양식 구성 요소의 내용을 인코딩 할 수 있습니다. // 업로드 된 파일 (post2)이 포함 된 양식 인 경우이 문장은 업로드 된 파일의 파일 이름으로 만 인코딩을 설정할 수 있습니다 (중국어 갈라진 코드 해결). 그러나 서버에서 일반 양식 구성 요소의 garbled 코드를 해결할 수는 없습니다 (인코딩을 설정할 수 없습니다) // 업로드 된 모든 파일에 디렉토리를 지정하십시오. String Path = GetServletContext (). GetRealPath ( "/Upload"); System.out.println ( "Path :"+Path); 파일 dir = 새 파일 (경로); if (! dir.exists ()) {dir.mkdirs (); } // 임시 파일 버퍼 크기 설정-8K 버퍼, 임시 파일 주소 diskFileItemFactory f = new DiskFileItemFactory (1024*8, 새 파일 ( "d :/a")); // 도구 업로드 servletfileUpload 업로드 = 새로운 servletfileUpload (f); upload.setfilesizemax (1024*1024*5); // 업로드 된 최대 업로드 된 단일 파일을 5m upload.setSizemax (1024*1024*8)로 설정합니다. // 업로드 된 모든 파일 크기의 합을 8m으로 설정하십시오. // 구문 분석 도구를 사용하여 {list <fileItem> list = upload.parserequest (request); for (fileitem fi : list) {if ((fi.isformfield ())) {// 일반 양식 구성 요소 인 경우 : Checkbox, Radio, Password ... // String desc = fi.getString (); System.out.println ( "fi.getString () :"+fi.getString ()); // 두 번째 단계 문자열 desc = fi.getString ( "UTF-8"); //이 문장은 일반 양식 구성 요소 System.out.println의 내용 인코딩을 설정합니다 ( "인코딩 후 :"+desc); } else {string ext = fi.getName (). substring (fi.getName (). lastIndexOf ( ".")); //. 문자열 filename = uuid+ext; //fi.getInputStream ()은 실제 파일 정보 파일 파일 itils.copyInputStreamTofile (fi.getInputStream (), 새 파일 (path+"/"+filename)); // write it alive}}} catch (fileUploadeXception e) {printstacktrace (); }}}정보 업로드 :
결과 업로드 :
Apache 파일 업로드 도구를 사용하여 파일 업로드 3 (파일 분석)을 달성하십시오.
해시 디렉토리로 파일 스토리지 최적화 :
해시 디렉토리는 파일 스토리지 성능을 최적화하는 메소드입니다. Windows이든 Linux이든 NTFS 또는 EXT3이든 각 디렉토리에서 수용 할 수있는 항목의 수는 제한적입니다.
저장할 수는 없지만 프로젝트 수가 너무 커지면 파일 인덱싱 속도가 줄어 듭니다.
따라서 디렉토리에 저장해야 할 파일의 수를 평가해야합니다. 너무 많이 절약하면 성능에 영향을 미치지 만 너무 적게 절약하면 너무 많은 디렉토리와 공간 낭비가 발생합니다. 따라서 큰 배치의 파일을 저장할 때
다른 하위 디렉토리에서 파일을 더 균등하게 "파괴"하여 각 레벨의 인덱스 속도를 향상시킬 수있는 알고리즘이 있습니다. 이 알고리즘은 해시입니다. 일반적으로 사용되는 MD5, SHA1 등은 해시 디렉토리로 사용할 수 있습니다. MD5는 또한 내 세션에서 SessionID의 첫 번째 및 9 자리 숫자를 얻는 데 사용되며, 이는 2 단계 해시 경로를 구성합니다. 즉, 시스템은 모든 세션 파일을 16 × 16 = 256 하위 디렉토리로 배포합니다. Linux의 각 디렉토리에 1000 개의 파일을 저장하면 최고의 공간 성능 비율을 달성 할 수 있다고 가정하면 시스템에는 256,000 개의 세션 파일이 동시에 사용될 수 있습니다.
패키지 cn.hncu.servlet; import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.list; import java.util.uuid; import javax.servlet.servletexception; import javax.servlet.httplet.httpp.httpervlet; javax.servlet.http.httpervletrequest; import javax.servlet.http.htttp.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.progresslistener; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import org.aplegevlead.servlet.servletfileupload; import org.aplegett ht ht {public void doget (httpservletrequest request, httpservletResponse 응답)은 servletexception, ioexception {response.setContentType ( "text/html"); // 업로드 된 파일 (post2)이 포함 된 양식 인 경우 드라마는 업로드 된 파일의 파일 이름으로 만 인코딩을 설정할 수 있지만 (중국의 갈색 블러 블 코드 해결) // post2 mode printwriter out = respint.getwriter ()에서 일반 양식 구성 요소의 중국어가 달린 코드를 해결할 수는 없습니다. out.println ( "<! doctype html public/"-// w3c // dtd html 4.01 Transitional // en/">"); out.println ( "<html>"); out.println ( "<head> <title> a servlet </title> </head>"); out.println ( "<body>"); // "?"이후에 부분을 얻습니다. get 메소드의 URL의 번호 // http : // localhost : 8080/servletdemo3/upload? name = jack & sex = male string qtr = request.getQueryString (); System.out.println ( "QSTR :"+QSTR); // qstr : name = jack & sex = male out.print ( "Get Get 업로드를 지원하지 않음"); out.println ( "</body>"); out.println ( "</html>"); out.flush (); out.close (); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {response.setContentType ( "text/html; charset = utf-8"); printwriter out = response.getwriter (); // 1 반 흑백 : 보호의 프론트 엔드는 Post1 메소드를 사용하여 제출됩니다. // 메소드 1 /* 문자열 유형 = request.getContentType (); if (! type.contains ( "multipart/form-data")) {out.println ( "지원되지 않은 양식 제출"); 반품; }*/// 방법 2 부울 부 : servletfileupload.ismultipartContent (요청); if (! boo) {out.println ( "지원되지 않은 양식 제출"); 반품; } // 1 단계 // 일반 양식 양식 (Post1), 다음 문장은 일반 양식 구성 요소의 내용을 인코딩하는 것을 설정할 수 있습니다. // 업로드 된 파일 (post2)이 포함 된 양식 인 경우이 문장은 업로드 된 파일의 파일 이름으로 만 인코딩을 설정할 수 있습니다 (중국어 갈라진 코드 해결). 그러나 서버에서 일반 양식 구성 요소의 garbled 코드를 해결할 수는 없습니다 (인코딩을 설정할 수 없습니다) // 업로드 된 모든 파일에 디렉토리를 지정하십시오. String Path = GetServletContext (). GetRealPath ( "/Upload"); System.out.println ( "Path :"+Path); 파일 dir = 새 파일 (경로); if (! dir.exists ()) {dir.mkdirs (); } // 임시 파일 버퍼 크기 설정-8K 버퍼, 임시 파일 주소 diskFileItemFactory f = new DiskFileItemFactory (1024*8, 새 파일 ( "d :/a")); // 도구 업로드 servletfileUpload 업로드 = 새로운 servletfileUpload (f); upload.setfilesizemax (1024*1024*5); // 업로드 된 최대 업로드 된 단일 파일을 5m upload.setSizemax (1024*1024*8)로 설정합니다. // 업로드 된 모든 파일 크기의 최대 합은 8m // ▲ 4 업로드 진행 진행 중과 업로드 업로드 업로드 .setProgressListener () {private double pre = 0d; @atederide // 매개 변수 1 : 얼마나 많은 바이트가 업로드되었는지 파라미터 2 : 얼마나 많은 바이 테이트가 공개적 인 void void (serial number) pitems) {double d = 1.0*pcontentlength*100; // 구문 분석 도구를 사용하여 구문 분석 {list <fileItem> list = upload.parserequest (request); for (fileitem fi : list) {if ((fi.isformfield ())) {// 일반 양식 구성 요소 인 경우 : Checkbox, Radio, Password ... // String desc = fi.getString (); System.out.println ( "fi.getString () :"+fi.getString ()); // 두 번째 단계 문자열 desc = fi.getString ( "UTF-8"); //이 문장은 일반 양식 구성 요소 시스템의 컨텐츠 인코딩을 설정합니다. } else {// protect : if (fi.getSize () <= 0) {계속; // 다음 파일 읽기} system.out.println ( "파일 콘텐츠 유형 :"+fi.getContentType ()); // file/plain system.out.println (파일 이름 : ");"); ");"); c : /users/adl1/desktop/a.txt string ext = fi.getname (). substring (fi.getname (). lastIndexof ( ".")); //. txt String uuid = uuid.randomUuid (). toString (). 교체 ( "-", "); 문자열 filename = uuid+ext; // 파일 디렉토리 나 breaking 기술 문자열 dir1 = integer.tohexstring (uuid.hashcode () & 0x0f); 문자열 dir2 = integer.tohexstring ((uuid.hashcode () & 0xf0) >> 4); //fi.getInputStream ()은 실제 파일 정보 파일 파일 itils.copyInputStreamTofile (fi.getInputStream (), 새 파일 (path+"/"/"/"/"/"+dir1+"/"+dir2+"/"+filename); // writed alive}}} catch (fileUploadexception e) {e.printSctactrace (); }}}메시지를 깨십시오 :
결과 중단 :
File 1:
File 2:
업로드 진행의 원리를 보여줍니다
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.