Servlet 로 파일 업로드

Servlet 로 파일 업로드
원본 주소:http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm  
서버 에 HTML 폼 탭 을 통 해 파일 을 업로드 할 수 있 는 Servlet업로드 할 텍스트, 이미지 및 모든 파일 이 있 습 니 다.
파일 업로드 폼 만 들 기:
         아래 html 코드 는 업로드 폼 을 만 들 었 습 니 다.생 성 과정 은 다음 과 같은 몇 가 지 를 주의해 야 합 니 다:
l form 탭 의 method 속성 은 POST 로 설정 해 야 합 니 다. 즉, GET 방법 은 안 됩 니 다.
l form 탭 의 enctype 속성 은 multipart / form - data 로 설정 해 야 합 니 다.
l from 탭 의 action 속성 은 서버 배경 servlet 맵 경로 와 같 아야 합 니 다.다음 인 스 턴 스 는 Uploadservlet 을 사용 하여 파일 업 로드 를 실현 합 니 다.
l 파일 을 업로드 하려 면 < input type = "file"... / > 표 시 를 사용 해 야 합 니 다.여러 파일 을 업로드 하려 면 이름 속성 값 이 다른 < input type = "file"... / > 표 시 를 여러 개 포함해 야 합 니 다.The browser associates a Browse button with each of them。
File Uploading Form

File Upload:

Select a file to upload:


이상 코드 는 다음 과 같은 효 과 를 얻 을 수 있 습 니 다.로 컬 PC 에서 파일 을 선택 할 수 있 습 니 다."Upload File" 을 누 르 면 폼 은 선택 한 파일 과 함께 제출 됩 니 다.
배경 servlet:
아래 Uploadservlet servlet 은 업 로드 된 파일 을 받 아 < Tomcat - installation - directory > / webapps / data 폴 더 에 저장 합 니 다.이 폴 더 의 이름 은 외부 프로필 웹. xml 의 context - param 요소 내용 을 통 해 추가 할 수 있 습 니 다.코드 는 다음 과 같 습 니 다:
<web-app>
....
<context-param> 
    <description>Location to store uploaded file</description> 
    <param-name>file-upload</param-name> 
    <param-value>
         c:"apache-tomcat-5.5.29"webapps"data"
     </param-value> 
</context-param>
....
</web-app>

         다음은 다 중 파일 동시 업로드 기능 을 구현 한 UploadServlet.그 전에 다음 과 같은 몇 가 지 를 확인 해 야 합 니 다.
l 다음 인 스 턴 스 의존 F ileUpload 클래스 이기 때문에 최신 버 전의 comons - fileupload. x. x. jar 를 classpath 아래 에 두 어야 합 니 다.여기에서 다운로드 할 수 있 습 니 다:http://commons.apache.org/fileupload/。
l FileUpload 클래스 는 Commons IO 패키지 에 의존 하기 때문에 최신 버 전의 commons - fileupload. x. x. jar 를 classpath 아래 에 두 어야 합 니 다.여기에서 다운로드 할 수 있 습 니 다:http://commons.apache.org/io/。
l 다음 예 를 테스트 할 때 max FileSize 보다 작은 파일 을 업로드 해 야 합 니 다. 그렇지 않 으 면 업로드 할 수 없습니다.
l 미리 폴 더 를 건 의 했 는 지 확인 하 십시오: c: "temp 과 c:" apache - tomcat - 5.5.29 "webapps" data.
// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
 
public class UploadServlet extends HttpServlet {
   
   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;
 
   public void init( ){
      // Get the file location where it would be stored.
      filePath = 
             getServletContext().getInitParameter("file-upload"); 
   }
   public void doPost(HttpServletRequest request, 
               HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){
         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>"); 
         out.println("</head>");
         out.println("<body>");
         out.println("<p>No file uploaded</p>"); 
         out.println("</body>");
         out.println("</html>");
         return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:""temp"));
 
      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );
 
      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);
        
      // Process the uploaded file items
      Iterator i = fileItems.iterator();
 
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>"); 
      out.println("</head>");
      out.println("<body>");
      while ( i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )      
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("""") >= 0 ){
               file = new File( filePath + 
               fileName.substring( fileName.lastIndexOf(""""))) ;
            }else{
               file = new File( filePath + 
               fileName.substring(fileName.lastIndexOf("""")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {
        
        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   } 
}

       Servlet 컴 파일 및 실행
    위의 Uploadservlet 를 컴 파일 하고 웹. xml 에서 필요 한 실 체 를 만 듭 니 다. 다음 과 같 습 니 다.
<servlet>
   <servlet-name>UploadServlet</servlet-name>
   <servlet-class>UploadServlet</servlet-class>
</servlet>
 
<servlet-mapping>
   <servlet-name>UploadServlet</servlet-name>
   <url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

         현재 만 든 HTML 폼 을 사용 하여 파일 을 업로드 할 수 있 습 니 다.방문 하 다http://localhost:8080/UploadFile.htm브 라 우 저 에 서 는 업로드 하고 싶 은 모든 파일 을 로 컬 에서 업로드 할 수 있 습 니 다.
         servlet 스 크 립 트 가 성공 적 으로 실행 되 었 다 면, 파일 은 c: "apache - tomcat - 5.5.29" webapps "data" directory 폴 더 에 업로드 되 었 습 니 다.

좋은 웹페이지 즐겨찾기