1. 필수 패키지 :
1. Commons-FileUpload-1.2.1.jar :
주소를 다운로드하십시오
http://commons.apache.org/downloads/download_fileupload.cgi
2. Commons-IO-1.4.jar :
주소를 다운로드하십시오
http://commons.apache.org/downloads/download_io.cgi
2. 주목할만한 사항 :
ENCTYPE = "multipart/form-data"는 양식 양식에 추가되어야합니다
3. 코드 예제
1. JSP 코드 :
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtml 4.01 transitional // en" "http://www.w3.org/tr/tml/html 4/tml/html 4/tml 4.html/html 4.tml. <html> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"> <title> 업로드 </title> </head> <body> <form action = "uploadservlet"method = "post"acctart/form-data "> <table> <tabtion </camption> <tr. <td> name </td> <td> <입력 유형 = "text"name = "name"> </td> </tr> <tr> <td> age </td> <td> <input type = "text"name = "age"> </td> </td> </td> <td> <input type = "image"> "> td> <tr> <td> </td> <td> <입력 유형 = "제출"value = "제출"> </td> </tr> </table> </form> </body> </html>
2. 업로드 렛드 코드
패키지 서블리; import java.io.bufferedInputStream; import java.io.bufferedOutputStream; import java.io.file; import java.io.fileoutputStream; import java.io.ioexception; import java.io.writer; import java.util.iterator; Java.util.list 가져 오기; javax.servlet.servletexception import; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.fileuploadexception; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import org.apache.commons.fileupload.util.streams; / ** * SERVLET 업로드 * @Author Lisanlai * */ public class UploadServlet 확장 httpservlet {private static final long serialversionuid = 1L; public uploadservlet () {super (); } Protected void doget (httpservletrequest 요청, httpservletreponse 응답) servletexception, ioexception {this.dopost (요청, 응답); } @SuppressWarnings ( "확인되지 않은") 보호 된 void dopost (httpservletrequest 요청, httpservletResponse 응답)는 servletexception, ioexception {response.setContentType ( "text/html"); // 인코딩을 UTF-8로 설정하여 중국어 문자가 응답을 표시하도록합니다 .SetchAracterEncoding ( "UTF-8"); Writer o = response.getWriter (); /** * 먼저, enctype 양식이 멀티 파트/양식-데이터인지를 판단하면, 동시에 양식의 제출 방법이 post * method : ismultipartContent (요청) */if (servletfileupload.ismultipartContent (요청)) {request.setcharacterencoding ( "utf-8"); // 하드 디스크 파일 공장을 인스턴스화하여 업로드 구성 요소 ServletFileUpload DiskFileItemFactory Factory = New DiskFileItemFactory (); // 파일 스토리지에 대한 임시 폴더를 설정하면이 폴더는 실제로 파일 filedir = 새 파일 ( "../ webApps/fileUpload/tmp/"); if (filedir.isdirectory () && filedir.exists () == false) {filedir.mkdir (); } factory.setRepository (filedir); // 최대 메모리 점유 공장을 설정합니다 .SetSizEthreshold (1024000); // ServletFileUpload 생성 객체 ServletFileUpload SFU = New ServletFileUpload (Factory); sfu.setheaderencoding ( "UTF-8"); // 단일 파일의 최대 값을 설정 바이트 sfu.setfilesizemax (102400000); // 업로드 된 모든 파일의 합은 최대 바이트 SFU.setSizemax (204800000)입니다. 목록 <fileItem> 항목 = null; try {items = sfu.parserequest (요청); } catch (sizelimitexeceededException e) {System.out.println ( "파일 크기는 최대치를 초과"); } catch (fileUploadeXception e) {e.printstacktrace (); } // ITERATOR <fileItem> iter = items == null? null : items.iterator (); // 이미지 업로드 후에 저장된 경로 디렉토리 파일 이미지 = 새 파일 ( "d :/upload/images/"); if (images.exists () == false) {images.mkdirs (); } // 반복 항목 while (iter! = null && iter.hasnext ()) {fileItem item = (fileItem) iter.next (); // 전달 된 것이 일반 양식 필드 인 경우 (item.isformfield ()) {System.out.print ( "일반 양식 필드 :"); System.out.print (새 String (item.getfieldName ()) + ""); System.out.println (새 String (item.getString ( "UTF-8"))); } // 파일 필드 else if (! item.isformfield ()) {System.out.println ( "소스 사진 :" + item.getName ()); 문자열 filename = item.getName (). substring (item.getName (). lastIndexof ( "//")); bufferedInputStream in = new bufferedInputStream (item.getInputStream ()); // 파일은 d :/upload/images 디렉토리에 저장 되며이 디렉토리는 BufferedOutputStream out = new bufferedOutputStream (새 파일 (new file (images.getAbsolutePath ()+ filename))도 있어야합니다. streams.copy (in, out, true); O.Write ( "파일 업로드 성공"); }}}} else {system.out.println ( "form enctype type error"); }}}}} 3. web.xml
<? xml version = "1.0"encoding = "utf-8"?> <web-app xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns = "http://java.sun.com/xml/ns/javaee" xmlns : web = "http://java.sun.com/xml/ns/javaee"xmlns : web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_505_5.xsd"id = "webapp_id"version = "2.5"> <display-name> uploadtest </display-name> <clelefile> upload.jsp </welcome-file> </welcome-file-list> <servlet> <description> </desision> <display-name> 업로드 </display-name> <servlet-name> uploadservlet </servlet-name> <servlet-class> servlet.uploadservlet </servletsclest> <servlet-mapping> <Servlet-name> 업로드 </servlet-name> <url-pattern>/uploadservlet </url-pattern> </servlet-mapping> </web-app>
이 기사는 "Java 업로드 작업 기술의 요약"으로 편집되었으며 모든 사람들은 배우고 읽을 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.