특별한딸기이야기

요청 파라미터 처리(파일 업로드 처리) 본문

딸기 공부방/struts and spring

요청 파라미터 처리(파일 업로드 처리)

특별한녀석 2008. 11. 12. 15:29

// 수업시간에 이론 및 실습을 하지 않아 교재의 예제를 옮겨 놓습니다.
// 추후 개인적으로 실행시켜 보고 성공된 코드로 바꿀 수 있으면 바꾸도록 하죠.

insert.jsp

<%@ page contentType="text/html;charset=euc-kr"%>
<html>
<head>
</head>
<body>
<font size="3">
 게시물등록
</font>
<br/>
<form method="post" enctype="multipart/form-data" action="$(pageContext.request.contextPath)/board/board.do">
 글쓴이 :
<input type="text" name="wirter"/>
첨부파일(1) :
<input type="file" name="boardFiles[0]"/>
첨부파일(2) :
<input type="file" name="boardFiles[1]"/>
</form>
</body>
</html>

BoardForm.java

import org.apache.struts.action.*;
import org.apache.struts.upload.*;

public class BoardForm extends ActionForm
{
private String writer;
private FormFile[] boardFile = new FormFile[2];

public String getWriter()
{
return this.writer;
}

public void setWriter(String w)
{
this.writer = w;
}

public FormFile[] getBoardFile()
{
return this.boardFile;
}

public void setBoardFile(FormFile[] f)
{
this.boardFile = f;
}

BoardAction.java
//여러개의 요청을 처리하는 Action class다
// 함수 머릿부분 생략
BoardForm boardForm = (BoardForm)form;

String tempFileSaveDirectory = "C/temp/";

for(FormFile formFile : boardForm.getBoardFiles())
{
if(formFile.getFileSize()>0)
{
String tempFileName = UUID.randomUUID() + "_" + formFile.getFileName();
InputStream is = formFile.getInputStream();
FileOutputStream fos = new FileOutputStream(tempSaveDirectory + tempFileName);
int readybytes = -1;
byte[] data = new byte[1024];
while((readbytes = is.read(data, 0, 1024)) != -1)
{
fos.write(data, 0, readbytes);
}
fos.close();

return null;
}
}

struts-config.xml

// 상단 부분 생략
<struts-config>
<form-beans>
<form-bean name="boardForm" type="자바~"/>
</form-beans>
<action-mapping>
<action .. 앞의 부분과 유사 생략
</action-mapping>
</struts-config>