1. 파일 업로드의 원리
1. 파일 업로드 전제 조건 :
에이. 양식 양식의 방법은 게시해야합니다
비. 양식 양식의 ENCTYPE는 멀티 파트/양식 데이터 여야합니다 (사후 요청 방법과 요청 본문의 데이터 유형을 결정합니다).
기음. 양식에 제공된 입력 유형은 파일 유형 파일 업로드 도메인입니다.
2. 타사 구성 요소를 사용하여 파일 업로드를 달성하십시오
1. Commons-FileUpload 구성 요소 :
JAR : Commons-FileUpload.jar
Commons-Io.jar
2. 핵심 클래스 또는 인터페이스
DiskFileItemFactory : 환경을 설정하십시오
public void setsizethreshold (int sizethreshold) : 버퍼 크기를 설정합니다. 기본값은 10KB입니다.
업로드 된 파일이 버퍼 크기를 초과하면 FileUpload 구성 요소가 임시 파일 캐시를 사용하여 파일을 업로드합니다.
public void setRepository (java.io.file repository) : 임시 파일이 저장된 디렉토리를 설정하십시오. 기본적으로 시스템의 임시 파일 스토리지 디렉토리.
ServletfileUpload : Core 업로드 클래스 (기본 기능 : 요청의 신체 내용을 구문 분석)
Boolean ismultipartContent (httpservletrequest? request) : 사용자 양식의 ENCTYPE가 멀티 파트/양식 데이터 유형인지 결정합니다.
parserequest (httpservletrequest 요청) : 요청 본문의 내용을 구문 분석합니다.
setfilesizemax (4*1024*1024); // 단일 업로드 된 파일의 크기를 설정합니다
upload.setsizemax (6*1024*1024); // 총 파일 크기를 설정합니다
FileItem : 양식의 입력 필드를 나타냅니다.
부울 isformfield () : 정상 필드입니다
String getfieldName : 일반 필드의 필드 이름 가져 오기
String getString () : 일반 필드의 값을 얻습니다
inputStream getInputStream () : 업로드 된 필드의 입력 스트림을 가져옵니다
String getName () : 업로드 된 파일 이름을 가져옵니다
예 : 먼저 Web-INF 디렉토리에서 파일 폴더를 만듭니다. 즉, 모든 파일은 여기에 업로드해야합니다.
1. 파일의 실제 경로를 얻으십시오
String StorePath = GetServletContext (). getRealPath ( "/web-inf/files");
2. 환경을 설정하십시오
DiskFileItemFactory Factory = New DiskFileItemFactory (); // 기본 캐시 및 임시 파일 스토리지 장소는 어디에 있습니까?
3. 양식 전달 방법을 판단하십시오
부울 ismultipart = servletfileupload.ismultipartContent (요청); if (! ismultipart) {System.out.println ( "업로드 메소드 잘못!"); 반품; }4. 파일 업로드 핵심 클래스
ServletFileUpload 업로드 = 새로운 ServletFileUpload (공장); 5. 분석 // 구문 분석 목록 <fileItem> items = upload.parserequest (요청); for (fileItem item : items) {if (item.isformfield ()) {// 정상 필드, 문자열 필드 이름은 form = item.getfieldName (); // field string fieldValue = item.getString (); // 형성 정보 필드 값 system.out.println (fieldName+"="+fieldValue); } else // 파일 처리 {inputStream in = item.getInputStream (); // 파일 이름 업로드 c : /users/administrator/desktop/a.txt String name = item.getName (); // 그냥 a.txt string filename = name.substring (name.lastIndexof ( "//")+1); // 출력 스트림 구축 string string+"//"+filename; // 파일의 주소 저장 outputStream out = new FileOutputStream (StoreFile); 바이트 [] B = 새로운 바이트 [1024]; int len = -1; while ((len = in.read (b))! = -1) {out.write (b, 0, len); } in.close (); // 스트림을 닫아 out.close (); }}양식을 작성하십시오
<%@ page language = "java"import = "java.util.*"pageEncoding = "utf-8"%> <%string path = request.getContextPath (); String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.get.gteRverport () <! "-// w3c // dtml 4.01 과도기 // en"> <html> <head> <base href = "<%= basepath%>"> <title> 나의 jsp '1.jsp'시작 페이지 </title> <meta http-equiv = "pragma"content = "no-cache"> content = "no-cache"> <meta http-equiv = "만료"content = "0"> <meta http-equiv = "keywords"content = "keyword1, keyword2, keyword3"> <meta http-equiv = "description ="이것은 내 페이지입니다 ">-<link rel ="text/css " href = "styles.css">-> </head> <body> <form action = "$ {pagecontext.request.contextpath}/servlet/uploadservlet2"method = "post"enctype = "multipart/form-data"> username <input type = "text" "username"/> <br/ <input = "파일" " 이름 = "f1"/> <br/> <input type = "file"name = "f2"/> <br/> <입력 유형 = "제출"value = "save"/> </form> </body> </html>제출 서블릿을 작성하십시오 : UploadServlet2
package com.liuzhen.upload; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputStream; import java.io.outputStream; import java.util.list; import javax.servlet.servletexception; import javax.servlet.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; // 파일 업로드 공개 클래스 업로드 void doeprows (httpervletrequest). servletexception, ioexception {// 인코딩 요청을 설정합니다 .SetchAracterEncoding ( "UTF-8"); Response.setContentType ( "Text/Html; charset = utf-8"); {// 파일을 업로드 string storepath = getServletContext (). getRealPath ( "/web-inf/files"); // 환경 설정 DiskFileItemFactory Factory = New DiskFileItemFactory (); // 판사 양식 전송 방법 양식 ENCTERPE = 멀티 파트/양식-데이터 부울 ismultipart = servletfileUpload.ismultipartContent (요청); if (! ismultipart) {system.out.println ( "업로드 메소드가 잘못되었습니다!"); 반품; } servletfileUpload 업로드 = 새로운 ServletFileUpload (공장); // 구문 분석 목록 <FileItem> items = upload.parsEerequest (요청); for (fileItem item : items) {if (item.isformfield ()) {// 정상 필드, 문자열 필드 이름은 form = item.getfieldName (); // field string fieldValue = item.getString (); // 형성 정보 필드 값 system.out.println (fieldName+"="+fieldValue); } else // 파일 처리 {inputStream in = item.getInputStream (); // 파일 이름 업로드 c : /users/administrator/desktop/a.txt String name = item.getName (); // 그냥 a.txt string filename = name.substring (name.lastIndexof ( "//")+1); // 출력 스트림 구축 string string+"//"+filename; // 파일의 주소 저장 outputStream out = new FileOutputStream (StoreFile); 바이트 [] B = 새로운 바이트 [1024]; int len = -1; while ((len = in.read (b))! = -1) {out.write (b, 0, len); } in.close (); // 스트림을 닫아 out.close (); }}} catch (fileUploadexception e) {throw new runtimeexception (e); }} public void dopost (httpservletrequest 요청, httpservletreponse 응답) servletexception, ioexception {doget (요청, 응답); }}업로드 된 파일은 Tomcat 응용 프로그램에 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.