반응형

Commons-Fileupload 1.2


1.2 버젼이 2007.2.13에 새롭게배포되었습니다

1.1 이하단계 버젼과 달라진 점을 알아보도록 하지요

 

I. commons-fileupload 1.1

http://www.jakartaproject.com/article/jakarta/110887666654000

 

 

II. 다운로드 및 설치

 -. fileupload는 commons의 io가 필요합니다

commons-fileupload

http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi

commons-io

http://jakarta.apache.org/site/downloads/downloads_commons-io.cgi



III. 달라진점

 -. DiskFileUpload 가 Deprecated 되었습니다

 -. 리스너 추가를 통해 업로드 진행 상태를 파악할 수 있습니다(대용량 파일인 경우 유용)

 -. 비정상적인 업로드시 나타나는 중간 쓰레기 파일들을 제거할 수 있습니다

 

IV. 예제소스코드


upload.html

<form name=fileupload method=post action=./upload enctype="multipart/form-data">
 file : <input type=file name=file1><br>
 text : <input type=text name=text1><br>
 <input type=submit name=button1 value=submit>
</form>

web.xml

가비지 파일 cleaner에 사용되는 FileCleanerCleanup을 listener로 추가

샘플 코드에서 사용되는 서블릿 등록

<web-app>

   ...

 

   <listener>
       <listener-class>
           org.apache.commons.fileupload.servlet.FileCleanerCleanup
       </listener-class>
   </listener>


    ...


    <servlet>
        <servlet-name>uploadServlet</servlet-name>
        <servlet-class>UploadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>uploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>

    ...

</web-app>


UploadServlet.java


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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.ProgressListener;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadServlet extends HttpServlet {
   
    String upload_dir = null;
    public void init(ServletConfig config) throws ServletException {
          super.init(config); 
          upload_dir = config.getServletContext().getRealPath("/upload/");
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   

        // form type이 multipart/form-data 면 true 그렇지 않으면 false를 반환
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       
        if (isMultipart) {
            try {

                int yourMaxMemorySize = 1024 * 10;                 // threshold  값 설정
                long yourMaxRequestSize = 1024 * 1024 * 100;   //업로드 최대 사이즈 설정 (100M)

                File yourTempDirectory = new File(upload_dir);
               
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(yourMaxMemorySize);
                factory.setRepository(yourTempDirectory);               
   
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(yourMaxRequestSize);          // 임시 업로드 디렉토리 설정
                upload.setHeaderEncoding("EUC_KR");               // 인코딩 설정
               

                /**

                 *  업로드 진행 상태 출력 (Watching progress)

                */
                ProgressListener progressListener = new ProgressListener(){
                   private long megaBytes = -1;
                   public void update(long pBytesRead, long pContentLength, int pItems) {
                       long mBytes = pBytesRead / 1000000;
                       if (megaBytes == mBytes) {
                           return;
                       }
                       megaBytes = mBytes;
                       System.out.println("We are currently reading item " + pItems);
                       if (pContentLength == -1) {
                           System.out.println("So far, " + pBytesRead + " bytes have been read.");
                       } else {
                           System.out.println("So far, " + pBytesRead + " of " + pContentLength
                                              + " bytes have been read.");
                       }
                   }
                };
                upload.setProgressListener(progressListener);   // 진행상태 리스너 추가
   

                String fieldName = null;
                String fieldValue = null;
                String fileName = null;
                String contentType = null;
                long sizeInBytes = 0;

                List items = upload.parseRequest(request);               
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
   

                    // 정상적인 폼값 출력 및 처리
                    if (item.isFormField()) {
                        fieldName = item.getFieldName();
                        fieldValue = item.getString();
                       
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                        System.out.println("Field Name : "+fieldName);
                        System.out.println("Field Value : "+fieldValue);
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                       

                    // 업로드 파일 처리
                    } else {
                        fieldName = item.getFieldName();
                        fileName = item.getName();
                        contentType = item.getContentType();
                        sizeInBytes = item.getSize();
                       
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                        System.out.println("Field Name : "+fieldName);
                        System.out.println("File Name : "+fileName);
                        System.out.println("ContentType : "+contentType);
                        System.out.println("File Size : "+sizeInBytes);
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");

                        String savefile = fileName.substring(fileName.lastIndexOf("\\")+1, fileName.length());
                        File uploadedFile = new File(upload_dir+"\\"+savefile);
                        item.write(uploadedFile);
                    }
                }


            // 설정한 업로드 사이즈 초과시 exception 처리
            } catch (SizeLimitExceededException e) {
                e.printStackTrace();   

            // 업로드시 io등 이상 exception 처리
            } catch (FileUploadException e) {
                e.printStackTrace();

            // 기타 exception 처리
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }   
}


V. 실행결과

-----+-----+-----+-----+-----+-----+-----+-----+-----
Field Name : file1
File Name : C:\Program Backup\AromNet11a\AromNet.exe
ContentType : application/octet-stream
File Size : 274432
-----+-----+-----+-----+-----+-----+-----+-----+-----
-----+-----+-----+-----+-----+-----+-----+-----+-----
Field Name : text1
Field Value : this is test
-----+-----+-----+-----+-----+-----+-----+-----+-----

큰 파일을 업로드한 경우 업로드 상태 출력

We are currently reading item 0
So far, 4096 of 338043623 bytes have been read.
We are currently reading item 1
So far, 1003477 of 338043623 bytes have been read.
We are currently reading item 1
So far, 2002901 of 338043623 bytes have been read.
We are currently reading item 1
So far, 3002325 of 338043623 bytes have been read.
We are currently reading item 1
So far, 4001749 of 338043623 bytes have been read.
We are currently reading item 1
So far, 5001173 of 338043623 bytes have been read.
We are currently reading item 1
So far, 6000597 of 338043623 bytes have been read.
We are currently reading item 1
So far, 7000021 of 338043623 bytes have been read.
We are currently reading item 1
So far, 8003498 of 338043623 bytes have been read.
We are currently reading item 1
So far, 9002922 of 338043623 bytes have been read.
We are currently reading item 1
So far, 10002346 of 338043623 bytes have been read.
We are currently reading item 1
So far, 11001770 of 338043623 bytes have been read.
We are currently reading item 1
So far, 12001194 of 338043623 bytes have been read.
We are currently reading item 1
So far, 13000618 of 338043623 bytes have been read.
We are currently reading item 1
So far, 14000042 of 338043623 bytes have been read.
We are currently reading item 1
So far, 15003605 of 338043623 bytes have been read.
We are currently reading item 1
So far, 16003029 of 338043623 bytes have been read.

...


=============================================

본문서는 자유롭게 배포/복사 할수 있지만

이문서의 저자에 대한 언급을 삭제하시면 안됩니다

저자 : GoodBug (unicorn@jakartaproject.com)

최초 : http://www.jakartaproject.com 

=============================================


Posted by 1010