파일 업로드는 웹 응용 프로그램에서 매우 일반적입니다. Java 웹 환경에서 파일 업로드 기능을 구현하는 것은 매우 쉽습니다. 인터넷에서 파일 업로드를 위해 Java에 이미 개발 된 많은 구성 요소가 있기 때문입니다. 이 기사는 Java 웹 애플리케이션에 파일 업로드 기능을 추가하는 방법을 보여주기 위해 가장 Commons-Fileupload 구성 요소를 사용합니다.
Commons-FileUpload 구성 요소는 Apache의 오픈 소스 프로젝트 중 하나이며 http://commons.apache.org/fileupload/에서 다운로드 할 수 있습니다. 이 구성 요소는 간단하고 사용하기 쉽기 때문에 한 번에 하나 이상의 파일을 업로드 할 수 있으며 파일 크기를 제한 할 수 있습니다.
다운로드 후 Zip 패키지를 압축하고 Commons-FileUpload-1.x.jar를 Tomcat의 WebApps/WebApp/Web-Inf/Lib/에 복사하십시오. 디렉토리가 존재하지 않으면 자신의 디렉토리를 작성하십시오.
파일 업로드를 위해 새 업로드 ostervlet.java를 작성하십시오.
package com.liaoxuefeng.web; public class fileUploadServlet는 httpservlet {private string uploaddir = "c : // temp"; @override protected void dopost (httpservletrequest req, httpservletresponse resp) servletexception, ioexception {// todo :}}서블릿이 브라우저에서 발행 한 게시물 요청을 수신하면 파일 업로드가 dopost () 메소드에서 구현됩니다. FileItemiterator를 가로 지르고 각 FileItemStream을 가져와야합니다.
@OverRideProtected void dopost (httpservletrequest req, httpservletrepsonse resp) servletexception, ioexception {try {servletfileupload upload = new servletfileupload (); // 최대 파일 크기를 1MB로 설정합니다 : upload.setfilesizemax (1024 * 1024); FileItemiterator it = upload.getItemiterator (req); // 각 파일과 함께 처리 : while (it.hasnext ()) {fileItemStream item = it.next (); if (! item.isformfield ()) {// 파일 업로드입니다 : handleFileItem (item); }} req.getRequestDispatcher ( "success.jsp"). Forward (req, resp); } catch (fileUploadeXception e) {Throw New ServleTeXception ( "파일을 업로드 할 수 없음", e); }}handleFileItem () 메소드에서 업로드 된 파일의 입력 스트림을 읽은 다음 UPLoadDir에 작성하면 uuid에 의해 파일 이름이 무작위로 생성됩니다.
void handleFileItem (FileItemStream 항목)은 ioException {System.out.println ( "업로드 파일 :" + item.getName ()); file newUploadFile = 새 파일 (uploadDir + "/" + uuid.randomUuid (). toString ()); 바이트 [] 버퍼 = 새로운 바이트 [4096]; inputStream input = null; 출력 스트림 출력 = NULL; try {input = item.openstream (); output = new bufferedOutputStream (새 파일 아웃 putStream (newUploadFile)); for (;;) {int n = input.read (버퍼); if (n == (-1)) 파손; output.write (버퍼, 0, n); }} 마침내 {if (input! = null) {try {input.close (); } catch (ioException e) {}}}Web.xml 구성 파일에서 지정된 업로드 폴더를 읽으려면 init () 메소드에서 초기화 할 수 있습니다.
@overridepublic void init (servletconfig config) servletexception {super.init (config); this.uploaddir = config.getInitParameter ( "dir");}마지막으로 Web.xml에서 서블릿을 구성하십시오.
<? xml version = "1.0"encoding = "utf-8"?> <! doctype web-app public "-// Sun Microsystems, Inc.//dtd 웹 애플리케이션 2.3 // en" "http://java.sun.com/dtd/web-app_2_3.dtd"> <bertlet> <Servlet-name> 업로드-넷버 렛 </servlet-name> <servlet-class> com.liaoxuefeng.web.fileuploadservlet </servlet-class> </servlet> <servlet-name> uploadservlet </servlet-name> <url-pattern>/uploadn </url-pattern> </web-pattern>
서블릿을 구성한 후 Tomcat 또는 Resin을 시작하고 간단한 Index.htm 테스트를 작성하십시오.
<html> <body> <p> FileUploadServlet demo </p> <form name = "form1"action = "upload"method = "post"enctipe = "multipart/form-data"> <input type = "file"name = "file"/> <input type = "submit"name = "value"/> </html> </html> </html> </html>
action = "업로드"는 업로드 된 파일을 처리하는 FileUploadServlet의 매핑 URL을 지정합니다.
업로드가 성공하면 success.jsp가 표시됩니다. 그렇지 않으면 예외가 발생합니다. 업로드 된 파일 크기가 설정 한 1MB를 초과하면 filesizelimitexceedEdexception을 얻게됩니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.