Struts FormFile 기반 파일 업로드

파일 업로드 에 관 한 컨트롤 이 매우 많 을 수 있 습 니 다. 예 를 들 어 학습 에 사용 되 는 SmartUpload, 성능 이 매우 좋 은 COS 구성 요소, Apache 가 있 는 FileUpload 구성 요소, Struts 가 있 는 FormFile 구성 요소, Spring 업로드 파일 이 있 고 다른 개 발 된 컨트롤 도 있 습 니 다.만약 당신 이 Struts 를 사용한다 면, Struts FormFile 구성 요 소 를 기반 으로 하 는 것 이 좋 은 선택 일 것 입 니 다.      Struts FormFile 은 Struts ActionForm 과 잘 결합 되 어 사용 하기 도 매우 간단 하지만 여러 개의 첨부 파일 을 동시에 업로드 하 는 것 은 좀 번 거 롭 습 니 다!어쨌든 그것 은 좋 은 것 이다. 관건 은 모두 가 그 를 어떻게 보 느 냐 에 달 려 있다! 첫 번 째 단 계 는 새로운 Struts 프로젝트 를 만 들 고 FileUploadform 을 만 듭 니 다. FileUploadform 은 다음 과 같 습 니 다.
package zizz.struts;

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

/**
*   Struts FormFile     .
* @author chen yuzhe
*
*/
public class FileUploadForm extends ActionForm{
    
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -7794872310588861856L;
    
    /**
     *       
     */
    private FormFile uploadFile;

    public FormFile getUploadFile() {
        return uploadFile;
    }

    public void setUploadFile(FormFile uploadFile) {
        this.uploadFile = uploadFile;
    }
    
}



 
 두 번 째 단 계 는 업 로드 된 파일 을 처리 하고 서버 에 저 장 된 경 로 를 처리 하 는 Action 을 만 듭 니 다. FileUploadAction 파일 의 내용 은 다음 과 같 습 니 다.
package zizz.struts;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/**
*      Action,      FormFile                 .
* @author ZIZZ
*
* @Create-Time:2007-12-26   03:35:37
*/
public class FileUploadAction extends Action {
    
    /**
     *               
     */
    private static String UPLOAD_FILE_PATH = "c:/income/";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, 
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        FileUploadForm uploadForm = (FileUploadForm)form;
        //       
        FormFile uploadFile = uploadForm.getUploadFile();
        //     
        String fileName = uploadFile.getFileName();
        //      
        int fileSize = uploadFile.getFileSize();
        System.out.println("FileName = " + fileName);
        System.out.println("FileSize=" + fileSize);
        boolean result = true;
        try{
            //        
            InputStream is = uploadFile.getInputStream();
            //    
            uploadFile(fileName,is);
        }catch(IOException ex){
            ex.printStackTrace();
            //        ,          
            result = false;
        }
        if(result){
            return mapping.findForward("success");
        } else {
            return mapping.findForward("fail");
        }        
    }
    
    /**
     *     
     * @param fileName
     * @param is
     * @throws IOException
     */
    private void uploadFile(String fileName,InputStream is) throws IOException{
        OutputStream os = new FileOutputStream(UPLOAD_FILE_PATH + fileName);
        //8k    
        byte[] buffer = new byte[1024 * 8];
        //          
        int len;
        while((len=is.read(buffer))!=-1){
            //         
            os.write(buffer,0,len);
        }
        //     
        os.close();
        //     
        is.close();
    }

}

 
세 번 째 단계, 파일 업로드 jsp 파일 작성
<%@ page language="java" contentType="text/html; charset=GBK"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>      </title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
    <html:form action="/upload" enctype="multipart/form-data">
            :<html:file property="uploadFile"></html:file> 
        <html:submit value="    "></html:submit>
    </html:form>
  </body>
</html>

 
네 번 째 단계, struts - config. xml 파일 설정
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans>
      <form-bean name="fileUploadForm" type="zizz.struts.FileUploadForm"></form-bean>
  </form-beans>
  <global-exceptions />
  <global-forwards />
  <action-mappings>
      <action path="/upload" name="fileUploadForm" scope="request" type="zizz.struts.FileUploadAction">
          <forward name="success" path="/success.jsp" redirect="true"></forward>
          <forward name="fail" path="/fail.jsp" redirect="true"></forward>
      </action>
  </action-mappings>
  <message-resources parameter="zizz.struts.ApplicationResources" />
</struts-config>

 
 다섯 번 째 단계, 응용 시스템 발표, 테스트 결과 검사

좋은 웹페이지 즐겨찾기