카테고리 없음

Struts2 File Upload example

Soul-Learner 2011. 8. 3. 17:18

Struts2 File Upload example


struts.xml

<?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>
    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
    <constant name="struts.i18n.encoding" value="UTF-8"/>
    <constant name="struts.multipart.parser" value="jakarta"/>
    <constant name="struts.multipart.saveDir" value="C:\Temp"/>
    <constant name="struts.multipart.maxSize" value="10000000"/>
    <constant name="struts.devMode" value="true"/>
   
    <package name="upload" namespace="/upload" extends="struts-default">

        <action name="upload" class="upload.UploadAction">

            <result name="form">upload/uploadForm.jsp</result>
            <result name="success">upload/uploadSuccess.jsp</result>
        </action>
       
    </package>
   
</struts>

스트러츠의 코어 jar 파일 안에 있는 default.properties 파일에는 업로드파일의 크기를 2MB 이하만 가능하도록 다음과 같이 설정되어있다.

struts.multipart.maxSize=2097152

 2MB 이상의 파일 크기를 업로드하려면 WEB-INF/classes/struts.properties에 다음과 같이 설정해 주어야  한다. 다음은 4MB 크기의 파일까지 업로드 할 수 있도록 설정하는 예이다.

WEB-INF/classes/struts.properties파일에 2MB이상의 업로드파일 사이즈를 설정하는 예
struts.multipart.maxSize=4194304
 
참고) 1K bytes=1024(210)bytes, 1M bytes=1048576(220)bytes, 1G bytes=1073741824(230)bytes)


uploadForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Struts2를 이용한 파일업로드 입력폼</title>
</head>
<body><br/><br/><center>
<form method="post" action="upload.action" enctype="multipart/form-data">
<table border="1" cellspacing="0" width="400">
<tr><th>사번</th><td><input type="text" name="emp.empno" value="1111"/></td></tr>
<tr><th>이름</th><td><input type="text" name="emp.ename" value="홍길동"/></td></tr>
<tr><th>부서</th><td><input type="text" name="emp.deptno" value="30"/></td></tr>
<tr><th>급여</th><td><input type="text" name="emp.sal" value="2000"/></td></tr>
<tr><th>입사</th><td><input type="text" name="emp.hiredate" value="2010-07-20"/></td></tr>
<tr><th>사진</th><td><input type="file" name="uploads"></td></tr>
<tr><th>이력</th><td><input type="file" name="uploads"></td></tr>
<tr><td colspan="2"> </td></tr>
<tr><td colspan="2"><input type="submit" value="저 장"/> </td></tr>
</table>

</form>

</center>
</body>
</html>



UploadAction.java

package upload;

import java.io.File;
import java.util.*;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.Action;

public class UploadAction implements Action {

 Employee emp; // Domain Object
 
 List<File> uploads;
 List<String> uploadsContentType;
 List<String> uploadsFileName;
 
 @Override
 public String execute() throws Exception {

   if(emp==null) return "form"; // 업로드 폼에서 액션을 호출하지 않은 경우에는 업로드 폼을 보여준다
  // 인터셉터가 모든 업로드 절차를 수행하므로 나머지 작업은 임시 저장폴더에서 원하는 폴더로 파일을 복사하는 것이다
  for(int i=0;i<uploads.size();i++){
   File destFile = new File("D:/upload/"+uploadsFileName.get(i));
   FileUtils.copyFile(uploads.get(i), destFile);
  }
  return SUCCESS;
 }

 public Employee getEmp() {
  return emp;
 }

 public List<File> getUploads() {
  return uploads;
 }

 public List<String> getUploadsContentType() {
  return uploadsContentType;
 }

 public List<String> getUploadsFileName() {
  return uploadsFileName;
 }

 public void setEmp(Employee emp) {
  this.emp = emp;
 }

 public void setUploads(List<File> uploads) {
  this.uploads = uploads;
 }

 public void setUploadsContentType(List<String> uploadsContentType) {
  this.uploadsContentType = uploadsContentType;
 }

 public void setUploadsFileName(List<String> uploadsFileName) {
  this.uploadsFileName = uploadsFileName;
 }
}



uploadSuccess.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>업로드된 파일 확인</title>
</head>
<body><br/><br/><center>

<table border="1" cellspacing="0" width="400">
 <caption>서버측에 업로드된 파일현황</caption>
 <tr><th>파일명</th><th>파일타입</th><th>등 록</th></tr>
 <tr><td>${uploadsFileName[0]}</td><td>${uploadsContentType[0]}</td><td>${emp.ename}</td></tr>
 <tr><td>${uploadsFileName[1]}</td><td>${uploadsContentType[1]}</td><td></td></tr>
</table>

</center>
</body>
</html>


Employee.java

package upload;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Employee {
 
 private int empno;
 private String ename;
 private int deptno;
 private int sal;
 private String hiredate;
 
 public int getEmpno() {
  return empno;
 }
 public String getEname() {
  return ename;
 }
 public int getDeptno() {
  return deptno;
 }
 public int getSal() {
  return sal;
 }
 public String getHiredate() {
  return hiredate;
 }
 public void setEmpno(int empno) {
  this.empno = empno;
 }
 public void setEname(String ename) {
  this.ename = ename;
 }
 public void setDeptno(int deptno) {
  this.deptno = deptno;
 }
 public void setSal(int sal) {
  this.sal = sal;
 }
 public void setHiredate(String hiredate) {
   this.hiredate = hiredate; 
}
}


위와 같이 구성을 마치고 테스트할 때는 http://localhost:8080/프로젝트명/upload.action 으로 요청하면 업로드 폼이 출력된다


....................................................................
BasicStack
....................................................................

Interceptor firing order

When we say the first interceptor in the stack, we're referring to the first interceptor declared in the XML as reading from the top of the page down. Let's look at the declaration of the basicStack from struts-default.xml to see exactly what we mean.

<interceptor-stack name="basicStack">
  <interceptor-ref name="exception"/>
  <interceptor-ref name="servletConfig"/>
  <interceptor-ref name="prepare"/>
  <interceptor-ref name="checkbox"/>
  <interceptor-ref name="params"/>
  <interceptor-ref name="conversionError"/>
</interceptor-stack>

In the basicStack, the first interceptor to fire will be the exception interceptor. From here, each interceptor will fire in the same sequence as you would read down the page. So the last interceptor to fire will be the conversionError interceptor. After the result has rendered, the interceptors will each fire again, in reverse order, to give them the opportunity to do postprocessing.

Incidentally, the basicStack, not to be confused with the default defaultStack, is just a convenient chunk of common interceptors that the struts-default package makes available to you to ease the process of custom stack building in case you find that the defaultStack isn't quite what you need.