본문 바로가기
프로그래밍/struts

스트럿츠 파일 업로드

by Super User 2011. 2. 11.

프로젝트중 파일업로드가 필요해 인터넷을 누볐다. 하지만...

스트럿츠에선 multipartrequest 패키지가 안먹힌다.. 왜???

multipartrequest 를 사용하때 스트럿츠에서 request 를 한번 요청하는데 이때 잘못되는듯 하다... 정확한진 모르겠고...

그래서 선택한 방법은 formfile 로 받는 방법을 사용했다.

아!~ 여기선 멀티 파일업로드를 할것이다.. 파일 한개 올리는 것 보단... 멀티.. 좋다!~

아래에 있는 코드들을 고대로 복사해서 돌린다면 당연히 에러가난다...

블로그에 올리기위해서 요기 조기 편집한것이기때문에..

개개인의 취향에 맞게 잘 고쳐서 사용하면 되겠다.

 

<struts-config.xml>

요기서 할일은 폼빈 등록과 엑션에서 넘겨줄대 만든 폼빈을 사용하여 넘겨주면 된다.

 

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

    <form-beans>
      <form-bean name="eventForm" type="com.movierang.form.EventForm" />    
    </form-beans>

 <action-mappings>

  <action path="/event_writeAction"
              type="com.movierang.event.action.EventWirteAction"
              name="eventForm"
              scope="request"
              validate="true">
   <forward name="event_list" path="/event_list.jo" redirect="true"/> 
  </action>

    </action-mappings>

 <message-resources parameter="MessageResources" />

</struts-config>

 

 

<EventForm.java>

폼빈을 만든다. 개인의 취향에 맞게~

 

package com.movierang.form; //뭐..걍 패키지고..


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

 

public class EventForm extends ActionForm
{

 private List formfiles = new ArrayList();

//여기서 중요한것!!! 아래의 setFormfiles() 이름은 jsp페이지에서 파일업로드할때 file 의 name 값과 동일해야 한다.

//배우기론 위의 변수가 같아야 한다고 하는데.. 아닌것같다.. 낚였다..

 

public List getFormfiles(){
  return this.formfiles;
 }
//요녀석이.. 중용한놈이지... 요놈... setFormfiles jsp 페이지의 name같과 다르면 값이 안넘어간다..
 public void setFormfiles (int iIndex, FormFile file){
  this.formfiles.add(file);
 }

}

 

<eventwrite.jsp>

요기서 주의 할점은 위에서도 말했듯이 file의 name 값이 폼빈의 값과 동일 해야한다.

formfiles[0],formfiles[1],,, 원하는 파일갯수만큼 요렇게 주면 된다.

아! 파일업로드기때문에.. enctype="multipart/form-data" 은 꼭 써줘야 한다.!

 

<form method="post" name="writeform"  action="event_writeAction.jo" enctype="multipart/form-data">

<table>

<tr>

<td>파일1:<td><input type="file" name="formfiles[0]" ></td></tr>

<td>파일2:<td><input type="file" name="formfiles[1]" ></td></tr>

</table>

</form>

 

<eventwriteaction.java>

action에서 처리 할일은 폼빈을 통하여 넘오온 파일들은 자알!~ 처리해줌 된다.

아래의 패키지와 임포트는 알아서.. 대충 써주고~

 

package com.movierang.event.action;

 

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
 
import com.movierang.form.*;
import com.movierang.event.*;
import com.movierang.util.*;

import java.text.SimpleDateFormat;
import java.util.List;
import java.io.*;
 
public class EventWirteAction extends Action
{
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
   {
   Event_img ei = new Event_img(); //파일빈즈 파일의 원래이름, 타입, 저장할이름을 담는다.
   Event article = new Event(); //파일만 업로드 한다면 요건 필요 없다.
   EventForm eventform = (EventForm)form; //action에선 폼을 통하여 넘오값을 EventForm으로 객체를 만든다.

     //List로 myFiles객체를 생성한다.

     //getFormfiles 요건 폼빈에서 만든 파일업로드의 get메소드

   List myFiles = (List) eventform.getFormfiles();   

   PropertyUtils.copyProperties(article, eventform); //객체 복사를 한다.
   System.out.println("eventform.e_title==>"+eventform.getE_title());
   System.out.println("article.e_title==>"+article.getE_title());
   EventManager manager = EventManager.instance();
   //DB에 입력 값 넣기...
   int chk = manager.insertArticle(article);
   if( chk!=0){
    System.out.println("DB저장 완료!!!==>"+chk);
   
     for(int i=0 ; i<myFiles.size();i++){
     if(myFiles.get(i)!=null){
      FormFile myFile = (FormFile)myFiles.get(i);
      System.out.println("myFile의 이름==> "+myFile.getFileName());

      //파일업로드...
      String realName = "";
         String fileName = myFile.getFileName();
         String fileContextType = myFile.getContentType();
         int fileSize = myFile.getFileSize();
      System.out.println("fileName===>"+fileName);
     
         String path = "/upload";  // 업로드할 경로
         String realPath = "";
     
          //* 파일 업로드 시작  
         InputStream in = null;
         OutputStream os = null;
     

         // 파일 확장자 구하기
         String ext = myFile.getFileName();
     
         int last = 0;
         boolean findExt = false;
      
         while((last = ext.indexOf(".")) != -1) {
             findExt = true;
             ext = ext.substring(last+1);
         }
      
         // 파일 이름 중복 방지
         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");        
         String rndName = sdf.format(new java.util.Date()) + System.currentTimeMillis()+i;
          
         // 실제 저장될 파일 이름
         realName = findExt ? rndName + "." + ext : rndName;
         System.out.println("realName==>"+realName);


         // 실제 저장될 디렉토리 구하기(어디에 위치하든 페이지가 있는곳의 절대경로를 알수 있다.

         // 하지만 이클립스에서 실행시는 절대경로를 찾지 못한다.
         ServletContext application = getServlet().getServletContext();
         realPath= application.getRealPath(path);
         System.out.println("realpath==>"+realPath);
          
         // 실제로 저장될 파일 풀 경로
         File file = new File(realPath + "/" + realName);


         // 저장하기(복사)
         os = new FileOutputStream(file);
         in = myFile.getInputStream();
      
         int j=0;
         byte[] buffer = new byte[1024*4];
         while((j=in.read()) != -1) {
          os.write(j);
         }
         /*썸네일만들기
         File destFile = new File(realPath + "/small_" + realName);
      System.out.println("destFile==>"+destFile);
      //ImageUtil.resize(file, destFile, 150, ImageUtil.RATIO);
      ImageUtil.resize(file, destFile, 350, 150);
      */
           
         //event_img 객체에 담기
         ei.setEimg_num(chk);
         ei.setEimg_orgname(myFile.getFileName());
         ei.setEimg_filename(realName);
         ei.setEimg_filenum(i);
         ei.setEimg_filetype(myFile.getContentType());
        
         int fchk = manager.fileInsertArticle(ei);
         System.out.println("fchk==> "+fchk);
    }
     }
     return mapping.findForward("event_list");
   }     
 return null;
   }
}

 

 

요렇게 해서 스트럿츠 멀티 파일업로드 끝!~~~

출처 : http://blog.naver.com/lee5noda?Redirect=Log&logNo=130075391373