4.8 Handling file uploads

4.8.1 Accessing uploaded files through the request wrapper

  • multipart/form-data 로 선언되어 있다면 HttpServletRequest가 MultiPartRequestWrapper로 생성 됨

<form action="upload.action" enctype="multipart/form-data" method="post">
    <input type="file" name="doc"/>
    ...
</form>

  • 예제 소스

public class DocUpload extends ActionSupport implements ServletRequestAware {

    HttpServletRequest req;

    public void setServletRequest(HttpServletRequest req) {
        this.req = req;
    }
    
    public String execute() throws Exception {
        
        MultiPartRequestWrapper wrapper =  (MultiPartRequestWrapper) req;
        File doc = null;
        
        try {
            doc = wrapper.getFiles("doc")[0];
            String contentType = wrapper.getContentTypes("doc")[0];
            String filename = wrapper.getFilesystemNames("doc")[0];
            // do something with the file, content-type, and filename
        } finally {
            doc.delete();
        }
        return SUCCESS;
    }
}

4.8.2 Automating file uploads

  • FileUploadInterceptor 를 이용하여 자동으로 파일 업로드 한다.
  • HTML 의 file의 이름이 doc 일경우의 예제

public class DocUpload extends ActionSupport {

    File doc;
    //이름 지정 방식이 매우 중요하다. (name + ContentTyep, name+FileName)
    String docContentType;  
    String docFileName;
    
    public String execute() throws Exception {
        // do something with the file, content-type, and filename
        return SUCCESS;
    }
    
    public void setDoc(File doc) {
        this.doc = doc;
    }
    
    public void setDocContentType(String docContentType) {
        this.docContentType = docContentType;
    }
    
    public void setDocFileName(String docFileName) {
        this.docFileName = docFileName;
    }
}

4.8.3 Configuration settings

  • webwork.properties에 설정
  • webwork.multipart.parser : multipart request parser 설정. pell,cos, jakarta중에서 선택, jakarta 권장
  • webwork.multipart.saveDir : 임시파일이 저장되는 디렉토리
  • webwork.multipart.maxSize 최대 업로드 가능한 파일 사이즈. Defaults to 2097152

문서에 대하여

  • 이 문서의 내용은 Webwork In Action 교재를 스터디 하면서 정리한 내용 입니다.
  • 최초작성자 : 김정식
  • 최초작성일 : 2007년 9월 21일
  • 이 문서는 오라클클럽 자바 웹개발자 스터디 모임에서 작성하였습니다.
  • 이 문서를 다른 블로그나 홈페이지에 퍼가실 경우에는 출처를 꼭 밝혀 주시면 고맙겠습니다.~^\^