검색결과 리스트
글
struts2] multi upload
Multi Upload
1. web.xml 필터 등록
- singleupload에서 설정한것과 동일
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="multiUpload">
<result>/ex2/multiUpload.jsp</result>
</action>
<action name="multiUpload_ok" class="ex2.MultiUploadAction">
<result name="input">/ex2/multiUpload.jsp</result>
<result>/ex2/multiUploadResult.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. multiUpload.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="multiUpload_ok" enctype="multipart/form-data" theme="simple">
<b>멀티 파일 업로드 </b><hr>
File 1 : <s:file name="upload"/><br> //파일명을 동일하게 설정
File 2 : <s:file name="upload"/><br>
File 3 : <s:file name="upload"/><br>
<s:submit/>
</s:form>
5. MultiUploadAction.java
- ActionSupport 클래스를 상속받은 action클래스
- action클래스 (일반적인 setter/getter, execute()메소드로 구성됨)
- jsp페이지에서 action클래스가 불려질때 폼에서 전달된 값과 함께 자동적으로 execute()메서드가 호출됨
package ex2;
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
import ex1.FileService;
public class MultiUploadAction extends ActionSupport {
private File[] upload; // 멀티 업로드의 경우 배열로 받아 처리
private String[] uploadFileName,uploadContentType,serverFullPath;
public String execute() throws Exception{
serverFullPath = new String[upload.length];
//String basePath = getText("upload_folder"); //아래에 설정한 properties파일에서 내용을 가져옴
String basePath = "D:/jspwork/struts2_FileUpload/WebContent/fileUpload";
FileService fileService = new FileService();
for(int i =0 ; i<upload.length; i++){
serverFullPath[i] = fileService.saveFile(upload[i], basePath, uploadFileName[i]);
}
return SUCCESS;
}
}
6. MultiUploadAction.properties
- properties파일을 이용하여 값을 받아오게 설정할수 있다.
(action클래스명.xml 형식으로 작성시 struts에서 자동으로 호출됨)
upload_folder = D:/jspwork/struts2_FileUpload/WebContent/fileUpload
7. multiUploadResult.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MultiUpload</title>
</head>
<body>
<h2> 멀티 파일 업로드 결과 </h2>
<s:iterator value="upload" status="stat">
/*
<s:property>선언시 자동적으로 action클래스에 getter메서드가 호출됨
배열로 받기 때문에 iterator를 이용하여 출력
*/
<li>파일 <s:property value="%{#stat.index+1}"/></li>
<li>컨텐츠 타입<s:property value="%{uploadContentType[#stat.index]}"/></li>
<li>로컬 파일 이름<s:property value="%{uploadFileName[#stat.index]}"/></li>
<li>서버 전체 경로<s:property value="%{serverFullPath[#stat.index]}"/></li>
<li>임시 파일 이름<s:property value="%{upload[#stat.index]}"/></li>
<hr>
</s:iterator>
</body>
</html>
RECENT COMMENT