스트럿츠 2는 서버에 파일 업로드하기 위해서는 이 기능을 지원하는 IO 컴퍼넌트 ,

FileUpload 컴퍼넌트의 2가지 라이브러리가 필요하다.

commons-fileupload-1.2.1.jar

commons-io-1.4.jar


※Struts 2의 기본 설정 파일에서는 업로드 파일 크기를 2MB로 제한하고 있다.


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.i18n.encoding" value="UTF-8" />
	<constant name="struts.devMode" value="true" />
	
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		
	
	<action name="FileUploadForm" class="file.FileUploadAction">
      <result>/jsp/fileUpload.jsp</result>
    </action>
    <action name="FileUploadAction" class="file.FileUploadAction">
      <result name="input">/jsp/fileUpload.jsp</result>
      <result>/jsp/fileUploadOK.jsp</result>
    </action>
    
      
    
	<action name="FileList" class="file.FileListAction">
	    <result>/jsp/fileDownload.jsp</result>
	</action>		
    <action name="FileDownload" class="file.FileDownloadAction">
            <result type="stream">
                <param name="contentType">binary/octet-stream</param>
                <param name="contentLength">${contentLength}</param>
                <param name="contentDisposition">${contentDisposition}</param>
                <param name="inputName">inputStream</param>
                <param name="bufferSize">4096</param>
            </result>
    </action>  
    
 
	</package>
</struts>

struts.properties
struts.i18n.encoding=UTF-8
struts.multipart.maxSize=2097152
struts.devMode = true

jsp/fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 업로드</title>
</head>

<body>
  <h2>파일 업로드 입력 폼</h2>
  <s:form action="FileUploadAction" method="POST" enctype="multipart/form-data">
  <s:file name="upload" label="File"  size="50"/>
  <s:submit />
  </s:form>
</body>
</html>

jsp/fileUploadOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 업로드</title>
</head>

<body>
  <h2>파일 업로드 입력 완료</h2>

  <p>
    <ul>
    <li>ContentType: <s:property value="uploadContentType" /> / ${uploadContentType}</li>
    <li>FileName: <s:property value="uploadFileName" /></li>
    <li>File: <s:property value="upload" /></li>
    </ul>
  </p>

</body>
</html>
jsp/fileDownload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 다운 로드</title>
</head>

<body>
<h4>다운로드 목록</h4><hr>
다운로드 디렉토리 : <s:property value="BasePath"/> 
   
<ul>

<s:iterator value="listFile" status="stat">
	<s:url id="download" action="FileDownload">
		<s:param name="basePath" value="basePath" />
		<s:param name="fileName"><s:property value="listFile[#stat.index].name" /></s:param>
	</s:url>
	<li><s:a href="%{download}"><s:property value="listFile[#stat.index].name" /></s:a><br/></li>
</s:iterator>
</ul>
<br/>
* 파일 이름을 클릭하면 파일이 다운로드됩니다. 
</body>
</html>

FileListAction.java
package file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class FileListAction extends ActionSupport {
	
	private static final String BasePath = "C:/upload/";
	
	private List<File> listFile = new ArrayList<File>();
	private String basePath;
    
	public String execute() throws Exception {
		basePath = BasePath;
		File dir = new File(basePath);
		File[] files = dir.listFiles();
		
		if (null != files) {
			for (File f: files) {
				if (f.isFile()) {
					listFile.add(f);
				}
			}
		}		
		
		return SUCCESS;
	}

	public List getListFile() {
		return listFile;
	}
	public void setListFile(List<File> listFile) {
		this.listFile = listFile;
	}
	public String getBasePath() {
		return basePath;
	}
	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}
}

FileUpload.java
package file;

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.profiling.UtilTimerStack;

public class FileUploadAction extends ActionSupport {
	
	  private static final String UploadPath = "C:/upload/";

	  // 스트럿츠2 파일 업로드의 특징 : intercepter가 파일 객체의 3가지 정보를 셋팅합니다. 
	  private File upload; // <s:file name="upload" 파라미터
	  private String uploadContentType;
	  private String uploadFileName;
	  
	  File saveFile;
	  
	  @Override
	  public String execute() throws Exception {
		  //프로파일링 셋팅하자
		  UtilTimerStack.setActive(true);
		  
		    if(upload != null && upload.exists()){
		    	saveFile=new File(UploadPath+uploadFileName);
		    	FileUtils.copyFile(upload, saveFile); //왼쪽 것을 오른쪽으로 복사한다. 
		    }
		    return SUCCESS;
	  }

	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	
}

FileDownloadAction.java
package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import com.opensymphony.xwork2.ActionSupport;

public class FileDownloadAction extends ActionSupport {	
		
	private String basePath;
	private String fileName;              //파일의 이름
	private String contentType;          //스트림 타입
	private String contentDisposition;	 //스트림의 원래 이름
	private InputStream inputStream;  //스트림 데이터
	private long contentLength;          //스트림의 크기	

	public String execute() throws Exception {
	    	//inputPath
	    	String inputPath = basePath + "/" + fileName;

	    	//contentLength
	    	File f = new File(inputPath);
	    	setContentLength(f.length());
	    	
	    	//contentDisposition
	    	setContentDisposition("attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

	    	//inputStream    	
	    	setInputStream(new FileInputStream(inputPath));
	    	
	        return SUCCESS;
	    }

		public String getBasePath() {
			return basePath;
		}
		public void setBasePath(String basePath) {
			this.basePath = basePath;
		}
		public String getContentDisposition() {
			return contentDisposition;
		}
		public void setContentDisposition(String contentDisposition) {
			this.contentDisposition = contentDisposition;
		}
		public long getContentLength() {
			return contentLength;
		}
		public void setContentLength(long contentLength) {
			this.contentLength = contentLength;
		}
		public String getContentType() {
			return contentType;
		}
		public void setContentType(String contentType) {
			this.contentType = contentType;
		}
		public String getFileName() {
			return fileName;
		}
		public void setFileName(String fileName) {
			this.fileName = fileName;
		}
		public InputStream getInputStream() {
			return inputStream;
		}
		public void setInputStream(InputStream inputStream) {
			this.inputStream = inputStream;
		}
}









다중 파일 업로드


MultiUploadListAction.java
package file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class MultiUploadListAction extends ActionSupport {
	
	  private static final String UploadPath = "C:/upload/";

	  private List<File> uploads = new ArrayList<File>();
	  private List<String> uploadsFileName = new ArrayList<String>();
	  private List<String> uploadsContentType = new ArrayList<String>();
	  
	  File saveFile;
	  
	  @Override
	  public String execute() throws Exception {
		  for (int i = 0; i < uploads.size(); i++) {
		        File destFile = new File(UploadPath
		            + getUploadsFileName().get(i));
		        
		        FileUtils.copyFile(getUploads().get(i), destFile);
		  }
		  return SUCCESS;
	  }

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

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

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

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

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

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

	public File getSaveFile() {
		return saveFile;
	}

	public void setSaveFile(File saveFile) {
		this.saveFile = saveFile;
	}

	public static String getUploadPath() {
		return UploadPath;
	}	
}

struts.xml
<action name="MultiUploadListForm">
      <result>/jsp/multiUploadList.jsp</result>
    </action>
    <action name="MultiUploadListAction" class="file.MultiUploadListAction">
      <result>/jsp/multiUploadListOK.jsp</result>
    </action> 
multiUploadList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 업로드</title>
</head>

<body>
  <h2>다중파일 업로드 입력 폼 (리스트)</h2>
  <s:form action="MultiUploadListAction" method="POST" 
      enctype="multipart/form-data">
    <s:file label="File (1)" name="uploads" size="50"/>
    <s:file label="File (2)" name="uploads" size="50"/>
    <s:file label="FIle (3)" name="uploads" size="50"/>
    <s:submit />
  </s:form>
</body>
</html>

multiUploadListOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 업로드</title>
</head>

<body>
  <h2> 리스트를 이용한 다중 파일 업로드 입력 완료 화면 </h2>
  <s:iterator value="uploads" status="stat">
  File ( <s:property value="%{#stat.index + 1}" /> ) <br/>
   컨텐츠 타입 : 
   <s:property value="%{uploadsContentType[#stat.index]}" /> <br/>
   파일 이름 : 
   <s:property value="%{uploadsFileName[#stat.index]}" /> <br/>
   임시 파일 이름 :    
   <s:property value="%{uploads[#stat.index]}" /> <br/>
   <hr/>
 </s:iterator>
</body>
</html>



+ Recent posts