반응형
Struts 에서 파일 업로드 하는 법입니다.
왜 올리냐? 앞으로의 Ctrl+C , Ctrl+V 를 위해서 -_-v
jdk 1.6.0_13
tomcat 6.0.18
struts 1.3.10
프로젝트는 struts-blank-1.3.10.war 파일 Import 해서 생성 했고, jsp 에는 struts taglib를 사용했습니다.
form.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<!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>file upload</title>
</head>
<body>
<html:form action="/result" method="post" enctype="multipart/form-data">
subject : <html:text property="subject" /> <br />
file : <html:file property="att" /> <p />
<html:submit value="submit" />
</html:form>
</body>
</html>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<!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>file upload</title>
</head>
<body>
<html:form action="/result" method="post" enctype="multipart/form-data">
subject : <html:text property="subject" /> <br />
file : <html:file property="att" /> <p />
<html:submit value="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.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="formFileUpload" type="antop.FormFileUpload" />
</form-beans>
<global-exceptions> </global-exceptions>
<global-forwards> </global-forwards>
<action-mappings>
<action path="/result" type="antop.ActionFileUpload"
name="formFileUpload" input="/form.jsp" scope="request">
<forward name="result" path="/result.jsp"/>
</action>
</action-mappings>
<message-resources parameter="MessageResources" />
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/org/apache/struts/validator/validator-rules.xml,
/WEB-INF/validation.xml" />
</plug-in>
</struts-config>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="formFileUpload" type="antop.FormFileUpload" />
</form-beans>
<global-exceptions> </global-exceptions>
<global-forwards> </global-forwards>
<action-mappings>
<action path="/result" type="antop.ActionFileUpload"
name="formFileUpload" input="/form.jsp" scope="request">
<forward name="result" path="/result.jsp"/>
</action>
</action-mappings>
<message-resources parameter="MessageResources" />
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/org/apache/struts/validator/validator-rules.xml,
/WEB-INF/validation.xml" />
</plug-in>
</struts-config>
FormFileUpload.java
package antop;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class FormFileUpload extends ActionForm
{
private static final long serialVersionUID = 1;
private String subject;
private FormFile att;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public FormFile getAtt() {
return att;
}
public void setAtt(FormFile att) {
this.att = att;
}
}
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class FormFileUpload extends ActionForm
{
private static final long serialVersionUID = 1;
private String subject;
private FormFile att;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public FormFile getAtt() {
return att;
}
public void setAtt(FormFile att) {
this.att = att;
}
}
ActionFileUpload.java
package antop;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import javax.servlet.ServletContext;
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;
public class ActionFileUpload extends Action
{
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
FormFileUpload f = (FormFileUpload)form;
String subject = f.getSubject();
FormFile att = f.getAtt();
if(att != null)
{
String realName = "";
String fileName = att.getFileName();
String fileContextType = att.getContentType();
int fileSize = att.getFileSize();
String path = "/upload"; // 업로드할 경로
String realPath = "";
/*
* 파일 업로드 시작
*/
InputStream in = null;
OutputStream os = null;
try
{
// 파일 확장자 구하기
String ext = att.getFileName();
int last = 0;
boolean findExt = false;
while((last = ext.indexOf(".")) != -1) {
findExt = true;
ext = ext.substring(last+1);
}
// 파일 이름 중복 방지
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String rndName = sdf.format(new java.util.Date()) + System.currentTimeMillis();
// 실제 저장될 파일 이름
realName = findExt ? rndName + "." + ext : rndName;
// 실제 저장될 디렉토리 구하기
ServletContext application = getServlet().getServletContext();
realPath= application.getRealPath(path);
// 실제로 저장될 파일 풀 경로
File file = new File(realPath + "/" + realName);
// 저장하기(복사)
os = new BufferedOutputStream(new FileOutputStream(file));
in = att.getInputStream();
int i;
byte[] buffer = new byte[1024*4];
while((i=in.read(buffer, 0, 1024*4)) != -1) {
os.write(buffer, 0, i);
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try { if(os != null) os.close(); } catch (IOException ignore) { }
try { if(in != null) in.close(); } catch (IOException ignore) { }
}
/*
* 파일 업로드 끝
*/
request.setAttribute("realPath", realPath); // 실제 저장되는 풀경로
request.setAttribute("realName", realName); // 실제 저장된 파일 이름
request.setAttribute("fileName", fileName); // 업로드 했을때의 파일 이름
request.setAttribute("fileSize", fileSize); // 파일 사이즈
request.setAttribute("fileType", fileContextType); // 파일 종류
}
request.setAttribute("subject", subject); // 제목
return mapping.findForward("result");
}
}
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import javax.servlet.ServletContext;
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;
public class ActionFileUpload extends Action
{
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
FormFileUpload f = (FormFileUpload)form;
String subject = f.getSubject();
FormFile att = f.getAtt();
if(att != null)
{
String realName = "";
String fileName = att.getFileName();
String fileContextType = att.getContentType();
int fileSize = att.getFileSize();
String path = "/upload"; // 업로드할 경로
String realPath = "";
/*
* 파일 업로드 시작
*/
InputStream in = null;
OutputStream os = null;
try
{
// 파일 확장자 구하기
String ext = att.getFileName();
int last = 0;
boolean findExt = false;
while((last = ext.indexOf(".")) != -1) {
findExt = true;
ext = ext.substring(last+1);
}
// 파일 이름 중복 방지
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String rndName = sdf.format(new java.util.Date()) + System.currentTimeMillis();
// 실제 저장될 파일 이름
realName = findExt ? rndName + "." + ext : rndName;
// 실제 저장될 디렉토리 구하기
ServletContext application = getServlet().getServletContext();
realPath= application.getRealPath(path);
// 실제로 저장될 파일 풀 경로
File file = new File(realPath + "/" + realName);
// 저장하기(복사)
os = new BufferedOutputStream(new FileOutputStream(file));
in = att.getInputStream();
int i;
byte[] buffer = new byte[1024*4];
while((i=in.read(buffer, 0, 1024*4)) != -1) {
os.write(buffer, 0, i);
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try { if(os != null) os.close(); } catch (IOException ignore) { }
try { if(in != null) in.close(); } catch (IOException ignore) { }
}
/*
* 파일 업로드 끝
*/
request.setAttribute("realPath", realPath); // 실제 저장되는 풀경로
request.setAttribute("realName", realName); // 실제 저장된 파일 이름
request.setAttribute("fileName", fileName); // 업로드 했을때의 파일 이름
request.setAttribute("fileSize", fileSize); // 파일 사이즈
request.setAttribute("fileType", fileContextType); // 파일 종류
}
request.setAttribute("subject", subject); // 제목
return mapping.findForward("result");
}
}
result.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<!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>file upload result</title>
</head>
<body>
subject : <bean:write name="subject"/> <br />
realPath : <bean:write name="realPath"/> <br />
realName : <bean:write name="realName"/> <br />
fileName : <bean:write name="fileName"/> <br />
fileSize : <bean:write name="fileSize"/> <br />
fileType : <bean:write name="fileType"/>
</body>
</html>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<!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>file upload result</title>
</head>
<body>
subject : <bean:write name="subject"/> <br />
realPath : <bean:write name="realPath"/> <br />
realName : <bean:write name="realName"/> <br />
fileName : <bean:write name="fileName"/> <br />
fileSize : <bean:write name="fileSize"/> <br />
fileType : <bean:write name="fileType"/>
</body>
</html>
반응형
'Framework > Struts' 카테고리의 다른 글
*.jsp 접근 막기 (0) | 2009.09.03 |
---|---|
스트러츠(Struts) 기본 세팅 (6) | 2009.06.22 |