이 기사는 예제를 사용하여 Commons-FileUpload.jar를 사용하는 방법을 소개합니다. 파일의 업로드 기능을 용이하게하기 위해 Apache의 Commons-FileUpload.jar. 특정 내용은 다음과 같습니다
Apache의 Commons-FileUpload.jar를 Application에 Web-Inf/Lib 아래에 배치하면 사용할 준비가되었습니다. 다음 예제는 파일 업로드 기능을 사용하는 방법을 보여줍니다.
사용 된 FileUpload 버전은 1.2이고 환경은 eclipse3.3+myeclipse6.0입니다. FileUpload는 Commons IO를 기반으로하므로 프로젝트에 들어가기 전에 Web-Inf/Lib에서 Commons IO (Commons-IO-1.3.2.jar 사용)를 결정하십시오.
이 기사는 기사 끝의 첨부 파일에서 다운로드 할 수있는 예제 프로젝트입니다.
예 1
가장 간단한 예는 ServletFileUpload 정적 클래스를 통해 요청을 구문 분석하는 것입니다. 공장 클래스 FileItemFactory는 모든 필드를 파일 필드뿐만 아니라 Mulipart 클래스 형태로 처리합니다. getName () 파일 이름을 가져 오기, getString ()는 양식 데이터 컨텐츠를 가져 오며 isformfield ()는 일반적인 양식 항목인지 여부를 결정할 수 있습니다.
demo1.html
<html> <head> <meta http-equiv = "content-type"content = "text/html; charset = gb18030"> <title> 파일 업로드 </title> </head> <body> // 다중 공사 양식 데이터 여야합니다. <form name = "myform"action = "demo1.jsp"method = "post"enctype = "multipart/form-data"> 이름 : <br> <br> <input type = "text"name "size ="15 "> <br> 파일 : <br> <input type ="file "name ="myfile "> <br> <input type ="subm ""enmp ""sumb ""endam ""input 유형. </form> </body> </html>
demo1.jsp
<%@ page language = "java"contmenttype = "text/html; charset = gb18030"pageencoding = "gb18030"%> <%@ page import = "org.apache.commons.fileupload. import = "org.apache.commons.fileupload.disk.*"%> <%@ page import = "java.util.*"%> <! doctype html public "-// w3c // dtml 4.01 Transitional // en"> <%bolean ismultipart = servletfileupload.ismuttcontupload. 입력 요청은 멀티 파트 양식 데이터입니다. if (ismultipart == true) {fileItemFactory factory = new DiskFileItemFactory (); // 요청에 대한 DiskFileItemFactory 객체를 작성하고 요청을 구문 분석합니다. 구문 분석이 실행 된 후 모든 양식 항목이 목록에 저장됩니다. ServletFileUpload 업로드 = 새로운 ServletFileUpload (공장); 목록 <fileItem> items = upload.parserequest (요청); iterator <fileitem> itr = items.iterator (); while (itr.hasnext ()) {fileitem item = (fileitem) itr.next (); // 현재 프로젝트가 일반 양식 프로젝트인지 파일인지 확인하십시오. if (item.isformfield ()) {// 일반 양식 항목 인 경우 양식 내용을 표시하십시오. String fieldName = item.getFieldName (); if (fieldName.equals ( "name")) // type = "text"name = "name"out.print에 대한 응답 ( "필드 이름은" + item.getString ()); // 양식 내용을 표시합니다. out.print ( "<br>"); } else {// 파일을 업로드하는 경우 파일 이름을 표시하십시오. out.print ( "업로드 파일 이름은" + item.getName ()); out.print ( "<br>"); }}} else {out.print ( "EncType는 멀티 파트/Form-Data 여야합니다"); }%> <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = gb18030"> <title> 파일 업로드 </title> </head> </body> </html> 결과:
필드 이름 Isjeff
파일 이름 ISD :/C 언어 테스트 샘플/숙제 질문 .rar
예 2
지정된 디렉토리에 두 파일을 업로드하십시오.
demo2.html
<html> <head> <meta http-equiv = "content-type"content = "text/html; charset = gb18030"> <title> 파일 업로드 </title> </head> <body> <form name = "myform"action = "demo2.jsp"method = "post"inctype = "input type"> file "> file"> file "> 이름 = "myfile"> <br> file2 : <br> <input type = "file"name = "myfile"> <br> <br> <input type = "제출"name = "value ="commit "> </body> </html>
demo2.jsp
<%@ page language = "java"contmenttype = "text/html; charset = gb18030"pageencoding = "gb18030"%> <%@ page import = "org.apache.commons.fileupload. import = "org.apache.commons.fileupload.disk.*"%> <%@ page import = "java.util.*"%> <%@ page import = "java.io.*"%> <! doctype html public "-// w3c // dtd html 4.01 transital // en"> 부울 ismultipart = servletfileupload.ismultipartContent (요청); if (ismultipart == true) {try {fileItemFactory factory = new DiskFileItemFactory (); ServletFileUpload 업로드 = 새로운 ServletFileUpload (공장); 목록 <fileItem> items = upload.parsEerequest (request); // 모든 파일을 가져옵니다. 반대기 <fileItem> itr = items.iterator (); while (itr.hasnext ()) {// 각 파일 item = (fileItem) itr.next (); String filename = item.getName (); // 경로를 포함하여 파일 이름을 가져옵니다 if (filename! = null) {file fullFile = new File (item.getName ()); 파일 savedfile = 새 파일 (uploadPath, fullFile.getName ()); item.write (savedfile); }} out.print ( "업로드 성공"); } catch (예외 e) {e.printstacktrace (); }} else {out.println ( "EncType는 멀티 파트/Form-Data 여야합니다"); }%> <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = gb18030"> <title> 파일 업로드 </title> </head> </body> </html> 결과:
업로드 성공
현재 "d :/temp"에 업로드 한 두 파일을 볼 수 있습니다.
예 3
지정된 디렉토리에 파일을 업로드하고 파일 크기를 제한하십시오.
demo3.html
<html> <head> <meta http-equiv = "content-type"content = "text/html; charset = gb18030"> <title> 파일 업로드 </title> </head> <body> <form name = "myform"action = "demo3.jsp"method = "post"inctype = "inpe type/form-data"> 파일 "> 이름 = "myfile"> <br> <br> <입력 유형 = "제출"name = "제출"value = "commit"> </form> </body> </html>
demo3.jsp
<%@ page language = "java"contmenttype = "text/html; charset = gb18030"pageencoding = "gb18030"%> <%@ page import = "org.apache.commons.fileupload. import = "org.apache.commons.fileupload.disk.*"%> <%@ page import = "java.util.*"%> "%>"%> <%@ page import = "java.io.*"%> <! doctype html public "-// w3c // dtd html 4.01 transital // en"> <new up up up up up up-up up-up-up-up up old. file ( "d : // temp"); // 파일 디렉토리 업로드 if (! uploadpath.exists ()) {uploadpath.mkdirs (); } // 임시 파일 디렉토리 파일 TempPathFile = 새 파일 ( "d : // temp // buffer //"); if (! temppathfile.exists ()) {temppathfile.mkdirs (); } try {// 디스크 기반 파일에 대한 공장 생성 항목 diskFileItemFactory factory = new DiskFileItemFactory (); // 팩토리 제약 조건 설정 공장 .SetSizEthreshold (4096); // 버퍼 크기를 설정합니다. 여기 4KB Factory.setRepository (temppathfile); // 버퍼 디렉토리 설정 // 새 파일 만들기 업로드 핸들러 ServletFileUpload 업로드 = 새 ServletFileUpload (Factory); // 전체 요청 크기를 설정합니다. upload.SetSizEmax (4194304); // 최대 파일 크기를 설정합니다. 여기 4MB 목록 <fileItem> items = upload.parserequest (request); // 모든 파일을 가져옵니다. iterator <fileItem> i = items.iterator (); while (i.hasnext ()) {fileItem fi = (fileItem) i.next (); 문자열 filename = fi.getName (); if (filename! = null) {file fullFile = 새 파일 (fi.getName ()); 파일 savedfile = 새 파일 (uploadPath, fullFile .getName ()); fi.write (savedfile); }} out.print ( "업로드 성공"); } catch (예외 e) {e.printstacktrace (); }%> <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = gb18030"> <title> 파일 업로드 </title> </head> </body> </html> 예 4
서블릿을 사용하여 파일 업로드를 구현하십시오.
upload.java
패키지 com.zj.sample; import java.io.file; import java.io.ioexception; import java.util.iterator; import java.util.list; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.httpervletrequpt; import; javax.servlet.http.httpervletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servletfileupload; @SuppressWarnings ( "Serial") 공개 클래스 업로드 확장 httpservlet {private String uploadPath = "d : // temp"; // 파일 업로드를위한 디렉토리 개인 문자열 temppath = "d : // temp // buffer //"; // 임시 파일 디렉토리 파일 TempPathFile; @SuppressWarnings ( "확인되지 않은") public void dopost (httpservletrequest 요청, httpservletrepsonse 응답)는 ioexception, servletexception {// 디스크 기반 파일을위한 공장 생성 diskfileitemfactory factory = new diskfileitemfactory (); // 팩토리 제약 조건 설정 공장 .SetSizEthreshold (4096); // 버퍼 크기를 설정합니다. 여기 4KB Factory.setRepository (temppathfile); // 버퍼 디렉토리 설정 // 새 파일 만들기 업로드 핸들러 ServletFileUpload 업로드 = 새 ServletFileUpload (Factory); // 전체 요청 크기를 설정합니다. upload.SetSizEmax (4194304); // 최대 파일 크기를 설정합니다. 여기 4MB 목록 <fileItem> items = upload.parserequest (request); // 모든 파일을 가져옵니다. iterator <fileItem> i = items.iterator (); while (i.hasnext ()) {fileItem fi = (fileItem) i.next (); 문자열 filename = fi.getName (); if (filename! = null) {file fullFile = 새 파일 (fi.getName ()); 파일 savedfile = 새 파일 (uploadPath, fullFile.getName ()); fi.write (savedfile); }} system.out.print ( "업로드 성공"); } catch (예외 e) {// 오류 페이지를 점프 할 수 있습니다 e.printstacktrace (); }} public void init ()는 servleTeXception {file uploadFile = 새 파일 (uploadPath)을 던지 릅니다. if (! uploadfile.exists ()) {uploadfile.mkdirs (); } file temppathfile = 새 파일 (temppath); if (! temppathfile.exists ()) {temppathfile.mkdirs (); }}} demo4.html
<html> <head> <meta http-equiv = "content-type"content = "text/html; charset = gb18030"> <title> 파일 업로드 </title> </head> <body> // action = "fileUpload"는 <url-pattern>의 <url-pattern> 설정에 해당합니다. <form name = "myform"action = "fileUpload"method = "post"enctype = "multipart/form-data"> file : <br> <입력 유형 = "file"name = "myfile"> <br> <br> <input type = "submit"name = "value ="commit "> </body> </html>
web.xml
<Servlet> <Servlet-name> 업로드 </servlet-name> <servlet-class> com.zj.sample.upload </servlet-class> </servlet> <servlet-mapping> <servlet-name> 업로드 </servlet-name> <url-pattern>/fileUpload </url-pattern> </servlet-mapping>
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.