본문 바로가기
이카루스의 날개/JSP

commons-fileupload 로 파일 업로드 하기

by 윙혼 2007. 3. 6.
출처 : http://www.jspclub.co.kr

jsp는 파일 업로드 처리 할때 보통 자바로 만든 패키지를 이용합니다.
그중 하나가 commons-fileupload 입니다.


1)commons-fileupload 패키지 다운 받기

http://jakarta.apache.org/site/downloads/downloads_commons-fileupload.cgi
위 주소에서 Binary 의 1.1.1.zip을 다운 받습니다.

http://jakarta.apache.org/site/downloads/downloads_commons-io.cgi
위 주소에서 Binary 1.2.zip 을 다운 받습니다.

2)패키지 설치
다운 받은 1.1.1.zip 을 압축을 푼후 commons-fileupload-1.1.1.jar 파일만
현재홈드렉토리 /WEB-INF/lib 안에 넣습니다.

다운 받은 1.2.zip 압축을 푼후 commons-io-1.2.jar 파일만
현재홈드렉토리 /WEB-INF/lib 안에 넣습니다.

그리고 톰켓을 재시작합니다.

3)사용 예제

#전송폼#

<html>
<head></head>
<body>
<form name="frm" action="upload_proc.jsp" enctype="multipart/form-data" method="post">
<input type="text" name="title">
<input type="file" name="upfile">
<input type="submit">
</form>

</body>
</html>

#처리 페이지#
<%@  page  contentType="text/html;  charset=euc-kr"  import="java.util.*,  java.io.*,  org.apache.commons.fileupload.*,org.apache.commons.io.*"%>  

<%  
  String  path  =  "/home/www/upload/";  

  DiskFileUpload  upload  =  new  DiskFileUpload();  

  upload.setSizeMax(1000000);  //파일  업로드  최대  size  
  upload.setSizeThreshold(4096);//메모리에  저장할  최대  size  
  upload.setRepositoryPath(path  +  "temp");  //파일  임시  저장소  



  List  items  =  upload.parseRequest(request);  
  Iterator  iter  =  items.iterator();  

  while  (iter  .hasNext())  {  

    FileItem  item  =  (FileItem)iter  .next();  

    if(item.isFormField()){

      String  name  =  item.getFieldName();  
      String  value  =  item.getString();  
      out.println(name  +  "="  +  value);  

    }else{  

      String  fileFieldName  =  item.getName();
      String  fileName  =  item.getName();
      fileName  =  fileName.substring(fileName.lastIndexOf("\\")+1);
      long  fileSize  =  item.getSize();


      File  file  =  new  File(path  +  "/"  +  fileName);  
      item.write(file);


      out.println(fileFieldName  +  "="  +  fileName  );  
    } 

  } 


%>  

사용법에 관한 문서
http://jakarta.apache.org/commons/fileupload/using.html

댓글