[25] 파일업로드 테이블 설계
* 자료형 게시판
테이블명 : tb_pds
----------------------------------------------------------------------
CREATE TABLE tb_pds (
pdsno INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,wname VARCHAR(100) NOT NULL
,subject VARCHAR(100) NOT NULL
,regdate DATETIME NOT NULL
,passwd VARCHAR(15) NOT NULL
,readcnt INT NOT NULL DEFAULT 0
,filename VARCHAR(100) NOT NULL
,filesize BIGINT NOT NULL DEFAULT 0
);
----------------------------------------------------------------------
파일명 : pdsForm.jsp
----------------------------------------------------------------------
<%@ page contentType="text/html; charset=utf-8"%>
<%@ include file="./ssi.jsp" %>
<%
String ip = request.getRemoteAddr(); // Client IP 추출
%>
<html>
<head>
<title>파일업로드</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<Script Language='JavaScript'>
function checkData(f){ // f == document.frmData 객체
var msg; // 에러 메세지
var str; // 임시 문자열 저장 변수
// 파일명을 소문자로 변환
var ext = f.filename.value.toLowerCase();
/*
정규 표현식
/^\s*: 시작 문자가 탭, 공백, 개행인 경우
| : OR 문자는 두 정규 표현식에서의 선택을 허용
\s* : 문자가 탭, 공백, 개행인 경우
$/g : 패턴을 문장의 끝에 적용
\s*$/g: 문장의 끝에 있는 공백
*/
// alert('>>' + ' test test '.replace(/^\s*|\s*$/g,'') + '<<'); return false;
// 이름 앞뒤의 공백 제거
str = f.name.value.replace(/^\s*|\s*$/g,'');
// 이름의 길이를 비교
if (str.length == 0){
msg = '안내\n\n이름을 입력해 주십시오';
window.alert(msg);
f.name.focus();
return false;
}
// 제목 앞뒤의 공백 제거
str = f.subject.value.replace(/^\s*|\s*$/g,'');
if (str.length == 0){
msg = '안내\n\n제목을 입력해 주십시오';
window.alert(msg);
f.subject.focus();
return false;
}
// 이름 앞뒤의 공백 제거
str = f.filename.value.replace(/^\s*|\s*$/g,'');
// 이름의 길이를 비교
if (str.length == 0){
msg = '안내\n전송할 파일을 선택해 주십시오';
window.alert(msg);
f.filename.focus();
return false;
}
if (f.passwd.value.length < 4){
msg = '안내\n\n비밀번호는 4자이상 입력하셔야 합니다.';
window.alert(msg);
f.passwd.focus();
return false;
}
if (ext.lastIndexOf(".exe") > 0){
alert('파일의 확장자가 EXE 인것은 전송할 수 없습니다.');
f.filename.focus();
return false;
}
if (ext.lastIndexOf(".asp") > 0){
alert('파일의 확장자가 ASP 인것은 전송할 수 없습니다.');
f.filename.focus();
return false;
}
if (ext.lastIndexOf(".jsp") > 0){
alert('파일의 확장자가 JSP 인것은 전송할 수 없습니다.');
f.filename.focus();
return false;
}
if (ext.lastIndexOf(".php") > 0){
alert('파일의 확장자가 PHP 인것은 전송할 수 없습니다.');
f.filename.focus();
return false;
}
if (ext.lastIndexOf(".cgi") > 0){
alert('파일의 확장자가 CGI 인것은 전송할 수 없습니다.');
f.filename.focus();
return false;
}
if (ext.lastIndexOf(".dll") > 0){
alert('파일의 확장자가 DLL 인것은 전송할 수 없습니다.');
f.filename.focus();
return false;
}
if (ext.lastIndexOf(".jar") > 0){
alert('파일의 확장자가 JAR 인것은 전송할 수 없습니다.');
f.filename.focus();
return false;
}
return true;
}
</Script>
</head>
<body topmargin="0" leftmargin="0">
<!-- onSubmit() 이벤트는 서브밋 버튼을 클릭하면 호출됨
this : document.frmData
submit() ▶ onSubmit() 이벤트 발생 ▶ checkData(this) 호출
▶ true or false return ▶ if true ▶ submit() 진행
-->
<form name="frmData"
method="post"
enctype="multipart/form-data"
action="./pdsIns.jsp"
onSubmit="return checkData(this)">
<input type="hidden" name="ip" value="<%=ip%>">
<table border="0" align="center">
<tr>
<th colspan="2">파일 등록 (* 필수 입력사항)
</th>
</tr>
<tr>
<td colspan="2" height="30"> </td>
</tr>
<tr>
<th width="97">성명*</th>
<td width="567"><input type="text" name="wname" value='홍길동'> </td>
</tr>
<tr>
<th>내용*</th>
<td><textarea name="subject" rows='5' cols='50'>맛있는 요리 사진</textarea></td>
</tr>
<tr>
<th>파일명*</th>
<td><input type="file" name="filename" value="" size="55"></td>
</tr>
<tr>
<th>비밀번호*</th>
<td><input type="password" name="passwd" value='1234'></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="전송">
<input type="Reset" name="Submit2" value="다시쓰기">
<input type="button" name="btnList" value="목록"
onclick="javascript:location.href='./pdsList.jsp'">
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
----------------------------------------------------------------------
파일명 : pdsIns.jsp
----------------------------------------------------------------------
<%@ page contentType="text/html; charset=utf-8"%>
<%@ include file="./ssi.jsp" %>
<%
//------------------------------------------------------------
// 자료실 구현 부분 - 파일 업로드
// enctype="multipart/form-data" 로 보낸 데이터는
// request 객체로 받을 수 없음으로
// request 객체에 접근 할 수 있는 HttpServletRequestWrapper를 상속받은
// FileUploadRequestWrapper 클래스의 객체를 만들어 사용한다
//------------------------------------------------------------
UploadManager requestWrap = null;
requestWrap = new UploadManager(request, -1, -1, tempDir);
request = requestWrap;
String filename = ""; //업로드 파일명
// filename 은 전송 폼에 있는 file태그의 이름
FileItem fileItem = requestWrap.getFileItem("filename");// 전송된 파일 객체
long filesize = fileItem.getSize(); // 파일 사이즈
if (filesize > 0){ // 전송된 파일이 있다면 저장
filename = requestWrap.saveFile(fileItem, upDir);
}
//-------------------------------------------------------------------
%>
<%
String wname = request.getParameter("wname");
wname = Utility.getEncodingFileUpload12(wname);
String subject = request.getParameter("subject");
subject = Utility.getEncodingFileUpload12(subject);
pdsDTO.setWname(wname);
pdsDTO.setSubject(subject);
pdsDTO.setFilename(filename);
pdsDTO.setFilesize(filesize);
pdsDTO.setPasswd(request.getParameter("passwd"));
%>
<html>
<head>
<title>자료 올리기</title>
</head>
<body topmargin="0" leftmargin="0">
<%
boolean sw = pdsMgr.create(pdsDTO); // 글 추가
//?: 파일로 전달되는 인수의 시작을 표시
//&: 파일로 전달되는 인수들의 구분자 역활을 함
if(sw == true){
%>
<br><br>
이미지를 추가했습니다.
<br><br><br>
[<a href="./pdsForm.jsp">파일 계속 올리기</a>]
[<a href="./pdsList.jsp">파일 목록으로 가기</a>]
<%
}else{
out.println("<p><b>이미지 등록이 실패 했습니다.</b></p>");
out.println("<a href='Javascript:history.back()'>다시 입력</a>");
}
%>
</body>
</html>
----------------------------------------------------------------------
파일명 : ssi.jsp
----------------------------------------------------------------------
<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.util.*, java.io.*" %>
<%@ page import="www.pds.*, www.utility.*"%>
<%@ page import="org.apache.commons.fileupload.*" %>
<jsp:useBean id="pdsMgr" class="www.pds.PdsMgr" />
<jsp:useBean id="pdsDTO" class="www.pds.PdsDTO" />
<%
request.setCharacterEncoding("utf-8");
%>
<%
// ----------------------------------------------------------------------------------
// 다운로드 관련 부분
// ----------------------------------------------------------------------------------
// 파일 다운로드 폴더
//String downDir = "/storage";
// 파일 저장 폴더
String upDir = application.getRealPath("/storage");
System.out.println("upDir: " + upDir);
// 임시 저장 폴더
String tempDir = application.getRealPath("/temp");
// ----------------------------------------------------------------------------------
%>
<%
// ----------------------------------------------------------------------------------
// 검색 관련 부분
// ----------------------------------------------------------------------------------
//검색 컬럼값 추출, null --> ""
String col = Utility.checkNull(request.getParameter("col"));
//검색어 추출, null --> ""
String word = Utility.checkNull(request.getParameter("word"));
// ----------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------
// 페이징 관련 부분
// ----------------------------------------------------------------------------------
int nowPage = 0; //시작 페이지 번호는 0부터
if (request.getParameter("nowPage") != null) {
nowPage= Integer.parseInt(request.getParameter("nowPage"));
}
// ----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// col, word, nowPage를 GET방식으로 조합, url.toString()으로 사용
//----------------------------------------------------------------------------------
StringBuffer url= new StringBuffer();
url.append("col=" + col);
url.append("&word=" + Utility.getEncoding(word));
url.append("&nowPage=" + nowPage);
//----------------------------------------------------------------------------------
%>
<%!
public String br(String str){
return str + "<BR>";
}
public String br(int str){
return str + "<BR>";
}
public String br(double str){
return str + "<BR>";
}
%>
<script language="javascript">
function go(url){
location.href=url;
}
function goSearch(url){
location.href=url + '<%=url%>';
}
</script>
------------------------------------------------------------------------
파일명 : pdsList.jsp
------------------------------------------------------------------------
<%@ page contentType="text/html; charset=utf-8"%>
<%@ include file="./ssi.jsp" %>
<!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=utf-8" />
<title> pdsList.jsp </title>
</head>
<body>
<center>
** 파일 업로드 목록 **<br>
<table border=1>
<tr>
<td>번호</td>
<td>제목</td>
<td>파일명</td>
<td>작성자</td>
<td>조회수</td>
<td>작성일</td>
</tr>
<%
String root = request.getContextPath();//물리적 경로
String downDir = "/storage";
int totalCount=pdsMgr.recordCount();
List dataList = pdsMgr.list();
String date = Utility.getDate(); //오늘날짜
for (int i = 0;i < totalCount; i++) {
// dataBoardDTO 추출
pdsDTO = (PdsDTO)dataList.get(i);
//dataBoardDTO 객체의 값을 변수에 저장
String wname = pdsDTO.getWname();
String subject = pdsDTO.getSubject();
String regdate = (pdsDTO.getRegdate()).substring(0, 10);
int pdsno = pdsDTO.getPdsno();
int readcnt = pdsDTO.getReadcnt();
String filename = pdsDTO.getFilename();
long filesize = pdsDTO.getFilesize();
%>
<tr>
<td><%=pdsno%></td>
<td align="left">
<%
String dto_date = pdsDTO.getRegdate();
%>
<a href="./pdsRead.jsp?nowPage=<%=nowPage%>&pdsno=<%=pdsno%>"><%=subject%></a>
<%
if (dto_date.substring(0, 10).equals(date)){
out.print("<img src='./images/new.gif' border=0> ");
}
%>
</td>
<td>
<%
if (pdsDTO.getFilesize() > 0){ %>
<a href="<%=root%>/storage/<%=filename%>">
<img src='<%=root%>/storage/<%=Utility.getEncoding(pdsDTO.getFilename()) %>'
border='0'
width='80' height='80' />
</a>
<%
}else{
out.println(" ");
}
%>
</td>
<td><%=wname%></td>
<td><%=readcnt%></td>
<td><%=regdate%></td>
</tr>
<%
}
%>
</table>
<br>
전체글갯수 : <%=totalCount %>
<br><br>
<a href="./pdsForm.jsp">[게시판 등록]</a>
<br>
</center>
</body>
</html>
------------------------------------------------------------------------