일반적으로 서블릿을 사용하여 양식 요소를 처리 할 때 양식 요소는 모두 간단한 텍스트이며 Servlet은 request.getParameter ()를 사용하여 처리하기 쉽습니다. 그러나 양식에 파일 필드를 업로드하는 것과 같은 간단한 텍스트 이상의 것이 포함되어있는 경우 여전히 httpservletrequest 객체에서 직접 복합 양식의 각 하위 부위를 구문 분석하는 것이 매우 복잡한 작업입니다.
"Multipart/Form-Data"유형 데이터의 처리를 단순화하기 위해, 해당 구성 요소는 처리에 사용될 수 있으며, 이는 많은 코딩을 절약하고 재사용을 지원하며 매우 효율적입니다.
FileUpload, SmartUpload, COS 등의 Java 구성 요소도 있습니다.이 기사에서는 Apache의 FileUpload와 함께 설명합니다.
FileUpload를 사용하려면 먼저 해당 구성 요소를 다운로드해야합니다.
1.FileUpload 패키지 : http://commons.apache.org/fileupload/
2.io 패키지 : http://commons.apache.org/io/
다운로드 후 zip 패키지를 삭제하고 Commons-FileUpload-1.2.1.jar 및 Commons-IO-1.4.jar를 Tomcat의 WebApp/Web-Inf/Lib로 복사하십시오.
1. 양식 페이지 (양식의 ENCTYPE = "Multipart/Form -Data"를 지정하려면) -Upload.html
<html> <head> <title> upload </title> </head> </head> <body> <form name = "upload form"method = "post"enctype = "multipart/form-data"action = "upload"> <table> <tr> <td> <div align = "right"> user name : </div> </td> <input type = "텍스트" "30" "size" </td> </tr> <td> <td> <div align = "right"> 파일 업로드 1 : </div> </td> <td> input type = "file"name = "file1"size = "30"/> </td> </tr> <td> <div align = "Right"> <td> <td> <td> <td> <td> <td> <td> <td> 이름 = "file2"size = "30"/> </td> </tr> <td> <td> <입력 유형 = "제출"이름 = "제출"value = "value ="upload "> </td> <td> <입력 유형 ="reset "name ="value = "Reset"> </td> </table> </html> </html> </html> </html> </html> </html>
2. 서블릿 처리 양식 - 업로드 서비스
Package MyPack; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import org.apache.commons.fileupload.*; import org.apache.commons.fileupload.servlet. UploadServlet는 httpservlet {private String filepath; // 업로드 된 파일이 개인 문자열 인 TempFilePath 인 디렉토리; // 임시 파일이 저장되는 디렉토리 공개 void init (ServletConfig Config)는 servletexception {super.init (config); FilePath = config.getInitParameter ( "FilePath"); tempFilePath = config.getInitParameter ( "tempfilepath"); filepath = getServletContext (). getRealPath (FilePath); tempFilePath = getServletContext (). getRealPath (tempfilepath); } public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {response.setContentType ( "text/plain"); // 클라이언트 인쇄기에 응답 본문을 보내십시오. ontnet = response.getWriter (); 시도 {// 하드 디스크 기반 파일을 만듭니다. FileItem Factory DiskFileItemFactory 팩토리 = New DiskFileItemFactory (); // 데이터를 하드 디스크에 쓰는 데 사용되는 버퍼의 크기를 설정하십시오. 여기 4K 팩토리가 있습니다 .SetSizetHreshold (4*1024); // 임시 디렉토리 공장을 설정합니다 .setRepository (새 파일 (tempfilepath)); // 파일 업로드 프로세서 생성 ServletFileUpload 업로드 = New ServletFileUpload (Factory); // 업로드 할 수있는 파일의 최대 크기를 설정하십시오. 다음은 4m upload.setSizemax (4*1024*1024); list / * fileItem * / items = upload.parserequest (요청); 반복자 iter = items.iterator (); while (iter.hasnext ()) {fileItem item = (fileItem) iter.next (); if (item.isformfield ()) {processformfield (항목, 아웃넷); // 일반 양식 필드를 처리} else {processuploadedFile (항목, 아웃넷); // 파일 업로드 처리}} outnet.close (); } catch (예외 E) {Throw New ServleTeXception (e); }} private void processformfield (fileItem 항목, printwriter outnet) {string name = item.getfieldName (); 문자열 값 = item.getString (); Outnet.println (이름+":"+value+"/r/n"); } private void processuploadedFile (fileItem 항목, printwriter outnet)은 예외 {string filename = item.getName (); int index = filename.lastIndexof ( "//"); filename = filename.substring (index+1, filename.length ()); Long Filesize = item.getSize (); if (filename.equals ( "") && filesize == 0) return; File UploadedFile = 새 파일 (FilePath+"/"+filename); item.write (uploadedFile); Outnet.println (filename+"저장되었습니다."); Outnet.println ( ""+filename+"의 크기는"+filesize+"/r/n"); }} 서블릿은 web.xml에서 다음과 같이 구성됩니다.
<Servlet> <Servlet-name> 업로드 </servlet-name> <servlet-class> mypack.uploadservlet </servlet-class> <init-param> <param-name> filepath </param-name> <param- value> store </param- value> <init-param> <tent-param> empffath </param-name> <Param-value> temp </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> 업로드 </servlet-name> <url-pattern>/업로드 </url-pattern> </servlet-mapping>
이 시점에서 간단한 파일 업로드 기능이 완료되었습니다. 양식 페이지에 액세스하고 파일을 선택하고 파일 업로드를 클릭하십시오. 파일을 서버에 업로드하는 동안 파일을 데이터베이스에 저장하려면 파일 이름을 얻은 후 파일 이름을 데이터베이스에 저장하여 향후 파일 이름에 따라 사용자의 파일을 선택할 수 있습니다!
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.