struts 2008. 7. 29. 14:25

struts2] single upload

                      Single Upload


1. web.xml 필터 등록

    <filter>
         <filter-name>struts2</filter-name>
         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
   </filter>
   
   <filter-mapping>
         <filter-name>struts2</filter-name>
         <url-pattern>/*</url-pattern>
   </filter-mapping>
   

2.struts.xml / struts.properties 설정

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC '-//Apache Software Foundation//DTD Struts Configuration 2.0//EN'
'http://struts.apache.org/dtds/struts-2.0.dtd'>
<struts>
    <package name="defalut" extends="struts-default" namespace="">
       <action name="singleUpload">
           <result>/ex1/singleUpload.jsp</result>
       </action>      

      <action name="singleUpload_ok" class="ex1.SingleUploadAction">
           <result name="input">/ex1/singleUpload.jsp</result>
           <result>/ex1/singleUploadResult.jsp</result>
      </action>
   </package>
</struts>


3. FileService.java
    - 파일에 관한 처리가 이루어지는 클래스(저장폴더 생성 및 파일저장작업이 이루어지는 메서드정의)


package ex1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileService {
 
/*
    파일들이 저장될 폴더를 생성하는 메서드
    폴더가 존재하지않을경우 폴더생성
*/

 public void makeBasePath(String n){  
   File dir = new File(n);
   if(!dir.exists())  
    dir.mkdirs();    
  }
 
/*
      File, 저장경로(basePath),파일명을 인자로 받는 메서드
*/

  public String saveFile(File file, String basePath, String fileName) throws Exception{
   
   if(file == null || file.getName().equals("")||file.length()<1)
      return null;
   
   makeBasePath(basePath);  // 저장될 폴더 생성! 폴더존재시 수행하지않음
   
   String serverFullPath = basePath + System.getProperty("file.separator") + fileName; //파일명이 포함된 절대경로
 
   FileInputStream fis = new FileInputStream(file);  // 저장할 파일에 스트림 생성
   
   /*
      이제 위에 있는 스트림을 통해 읽은 자원을 저장할 스트림 생성
      FileOutputStream은 경로만 존재한다면 그 위치에 파일이 있든 없든 무조건 파일을 만든다.
    */
   FileOutputStream fos = new FileOutputStream(serverFullPath);  
   
   /*
     위에서 생성한 빈파일이 서버측에 생성되었으므로 준비된 스트림을 통하여 채워넣는다.
    */
   int readSize = 0 ;
   byte[] buf = new byte[1024];
   while((readSize = fis.read(buf))!=-1){
    fos.write(buf, 0, readSize); //준비된 스트림을 통해 쓴다.    
   }
   
    fos.close();
    fis.close();    
   return serverFullPath;
  }
}


4. singleUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"%>

<%@ taglib  prefix="s" uri="/struts-tags"%>
  <s:actionerror/>
      <font color="red"><s:fielderror/></font><!-- 유효성 검사 오류시 표현 -->
 
  <s:form method="post" action="singleUpload_ok" enctype="multipart/form-data">
   <b>파일업로드 </b><hr>
    <s:file name="upload"/>
    <s:submit/>
  </s:form>  



5. SingleUploadAction.java
      - ActionSupport 클래스를 상속받은 action클래스
      - action클래스 (일반적인 setter/getter, execute()메소드로 구성됨)
      - jsp페이지에서 action클래스가 불려질때 폼에서 전달된 값과 함께 자동적으로 execute()메서드가 호출됨


package ex1;

import java.io.File;

import com.opensymphony.xwork2.ActionSupport;

public class SingleUploadAction extends ActionSupport {
 
  private File upload;
  private String uploadFileName,uploadContentType,serverFullPath;

    public String execute() throws Exception {
    String basePath = "D:/jspwork/struts2_FileUpload/WebContent/fileUpload";
    FileService fileService = new FileService();
    serverFullPath = fileService.saveFile(upload, basePath, uploadFileName);
    return SUCCESS;    
  } 
}


6. SingleUploadAction-validation.xml
    - validation 설정을 하는 부분(action클래스명-validation.xml 형식으로 작성시 struts에서 자동으로 호출됨)
   
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC '-//OpenSymphony Group //XWork Validator 1.0.2//EN' 'http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd'>

<validators>
    <field name="upload">
        <field-validator type="fieldexpression">
            <param name="expression">
                <![CDATA[
                upload.length() > 0
                ]]>
            </param>
            <message>
                업로드할 파일을 선택하십시오.
            </message>
        </field-validator>
    </field>
</validators>


7. SingleUploadResult.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
   <h2> 단일 파일 업로드 결과 </h2>
   <li>컨텐츠 타입<s:property value="uploadContentType"/></li>
   <li>로컬 파일 이름<s:property value="uploadFileName"/></li>
   <li>서버 전체 경로입<s:property value="serverFullPath"/></li>
   <li>임시 파일 이름<s:property value="upload"/></li>  
</body>
</html>