본문 바로가기

JSP/Apache Upload 03

Apache Upload 03

이용자가 파일을 업로드하면 파일의 정보를 데이터베이스에 저장하고 현재까지 업로드된 모든 파일 정보를 데이터베이스에서 가져와서 pdsList.jsp에서 보여준다. response.sendRedirect()를 사용하여 리스트를 보여주는 페이지로 이동을 하게 한다. 데이터베이스에서 리스트를 가져 올때는 FileInfo 라는 클래스를 DTO로 하여 Vector에 담아 JSP로 전달한다. 데이터베이스 관련 코드는 모두 PdsDAO 클래스 안에 선언한다.

uploadForm.html

<html>
 <head><title>Upload page</title>
 <style type="text/css">
 table{
  font-size:80%;
  text-decoration:none;
 }
 .textbox {
  border:1px solid;
  width:200px;
 }
 .filebox{
  border:1px solid;
  width:500px;
 }
 .desc{
  border:1px solid;
  width:400px;
 }
 </style>
 </head>
 <body><p><center>
 <form action="apacheUpload.jsp" method="post" enctype="multipart/form-data" name="form1">
   <table border=0 cellspacing=0 bgcolor=orange><tr><td>
   <table border=0 cellspacing=0 cellpadding=3 bgcolor=white>
    <tr><th align="center" colspan=2>Multiple file Upload</th></tr>
    <tr><th align="right">올린이</th><td align="left"><input class="textbox" type="text" name="name" value="김창운"></td></tr>
    <tr><th align="right">설명</th><td align="left"><input class="desc" type="text" name="desc" value="테스트용 업로드 파일"></td></tr>
    <tr><th align="right">File 1</th><td align="left"><input class="filebox" name="file" type="file"><td></tr>
    <tr><th align="right">File 2</th><td align="left"><input class="filebox" name="file" type="file""></td></tr>
    <tr><th align="right">File 3</th><td align="left"><input class="filebox" name="file" type="file""></td></tr>
    <tr><td colspan=2 align="center"><input type="submit" name="Submit" value="Submit files"></td></tr>
    </table>
    </td></tr></table>
 </form>
 </center>
 </body>
 </html>


apacheUpload.jsp

<%@ page contentType="text/html;charset=KSC5601"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>

<jsp:useBean id="pdsDAO" class="upload.PdsDAO" scope="session"/>

<%
 String author = null;
 String descr = null;
 String fileName=null;
 
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 if (!isMultipart) {
 }else {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;
    try {
       items = upload.parseRequest(request);
    } catch (FileUploadException e) {
     out.println("에러 1: "+e);
    }
    Iterator itr = items.iterator();
    while (itr.hasNext()) {
      FileItem item = (FileItem) itr.next();
      if (item.isFormField()) { // 파일이 아닌 폼필드에 입력한 내용을 가져옴.
        if(item!=null && item.getFieldName().equals("name")) {
          String name = item.getString();//form field 안에 입력한 데이터를 가져옴
          name = new String(name.getBytes("8859_1"), "KSC5601");
          out.println("전송자:"+name+"<br>");
          author = name;
        }else if(item!=null && item.getFieldName().equals("desc")) {
          String desc = item.getString();
          desc = new String(desc.getBytes("8859_1"), "KSC5601");
          out.println("파일에 대한 설명:"+desc+"<br>");
          descr = desc;
        }
     } else { // 폼 필드가 아니고 파일인 경우
    try {
       String itemName = item.getName();//로컬 시스템 상의 파일경로 및 파일 이름 포함
       System.out.println("itemName:"+itemName);
       System.out.println("fieldName:"+item.getFieldName());
       if(itemName==null || itemName.equals("")) continue;
       fileName = FilenameUtils.getName(itemName);// 경로없이 파일이름만 추출함
       System.out.println("fileName:"+fileName);

       // 전송된 파일을 서버의 하드디스크에 저장하기 위한 절차
       File savedFile = new File("D:/upload/"+fileName);
       item.write(savedFile);// 지정 경로에 파일을 저장함

       // 데이터베이스에 파일관련 정보를 저장하기 위한 절차
       pdsDAO.setName(author);
       pdsDAO.setDescr(descr);
       pdsDAO.setFileName(fileName);
       pdsDAO.insert();

    } catch (Exception e) {
       out.println("서버에 파일 저장중 에러: "+e);
      }
   }
  }
 }
 // 저장된 리스트를 모두 보여주기 위해 다른 뷰로 이동한다
 response.sendRedirect("/WebTest/pdsList.jsp");
%>

PdsDAO.java

package upload;

import java.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.util.*;

public class PdsDAO {
 private String name, descr, fileName;
 
 public PdsDAO(){}
 
 public PdsDAO(String name, String descr, String fileName) {
  this.name=name;
  this.descr=descr;
  this.fileName=fileName;
 }

 private Connection getConnection()  throws javax.naming.NamingException, java.sql.SQLException {
  Context initCtx = new InitialContext();
   /*
  Context envContext  = (Context)initContext.lookup("java:/comp/env");
  DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
  */
  DataSource ds =  (DataSource)initCtx.lookup("java:comp/env/jdbc/myoracle");
  return ds.getConnection();
 }
 
 public void setName(String name){
  this.name=name;
 }
 
 public void setDescr(String descr){
  this.descr=descr;
 }
 
 public void setFileName(String fileName){
  this.fileName=fileName;
 }
 
 public void insert() throws javax.naming.NamingException, java.sql.SQLException {
  Connection conn = getConnection();
  String sql = "insert into pds values(pds_num.nextval, ?,?,?,sysdate)";
  PreparedStatement pstmt = conn.prepareStatement(sql);
  pstmt.setString(1, name);
  pstmt.setString(2, descr);
  pstmt.setString(3, fileName);
  pstmt.executeUpdate();
  pstmt.close();
  conn.close();
 }
 
 public Vector<FileInfo> getList() throws javax.naming.NamingException, java.sql.SQLException {
  Connection conn = getConnection();
  String sql = "select * from pds";
  PreparedStatement pstmt = conn.prepareStatement(sql);
  ResultSet rs = pstmt.executeQuery();
  Vector<FileInfo> v = new Vector<FileInfo>();
  while(rs.next()){
   v.add(new FileInfo(rs.getInt("num"), rs.getString("name"), rs.getString("descr"), rs.getString("fileName"), rs.getString("up_date")));
  }
  return v;
 }
}

pdsList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="java.util.*" %>
<%@ page import="upload.FileInfo"%>

<jsp:useBean id="pdsDAO" class="upload.PdsDAO" scope="session"/>
<html>
<head>
<title>PDS List</title>
<style type="text/css">
TABLE{
 font-size:65%;
}
</style>
</head>
<body><p><center>
자료실 목록
<hr width=70%><p>
<table border=1 cellspacing=0>
<tr><th>번호</th><th>작성자</th><th>설 명</th><th>파일명</th><th>날짜</th></tr>
<%
 Vector<FileInfo> v = pdsDAO.getList();
 for(int i=0;i<v.size();i++) { %>
  <tr><td><%=v.get(i).getNum()%> </td><td><%=v.get(i).getName() %></td>
  <td><%=v.get(i).getDescr()%></td><td><%=v.get(i).getFileName()%></td>
  <td><%=v.get(i).getDate()%></td></tr>
<%}
%>
</table>
</center>
</body>
</html>


FileInfo.java

package upload;

public class FileInfo {
 private int num;
 private String name, descr, fileName, up_date;

 public FileInfo(){}
 
 public FileInfo(int num, String name, String descr, String fileName, String up_date) {
  this.num=num;
  this.name=name;
  this.descr=descr;
  this.fileName=fileName;
  this.up_date=up_date;
 }
 
 public int getNum(){
  return num;
 }
 
 public String getName(){
  return name;
 }
 
 public String getDescr(){
  return descr;
 }
 
 public String getFileName(){
  return fileName;
 }
 
 public String getDate(){
  return up_date;
 }
}