태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.

Commons fileUpload

JSP/Advance 2008/07/31 20:50

UploadWriteForm.jsp  /  UploadWriteProc.jsp   / 
FileUpload.java  / DownloadServlet.java  / BoardUtils.java


====================   UploadWriteForm.jsp  ======================



<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<html>
   <head>
     <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
     <title>Insert title here</title>
   </head>
   <body>
      <form action="UploadWriteProc.jsp" method="post" enctype="multipart/form-data">
         <input typw="text" name="age">
         <input type="file" name="upFile">
         <input type="submit" name = "button" value="Submit">
      </form>
   </body>
</html>



====================   UploadWriteProc.jsp  ======================

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="upload.FileUpload,java.util.*" %>
<!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>Insert title here</title>
</head>
<body>
<%
FileUpload fileUpload = new FileUpload(request, "C:\\kjy\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\chapter13\\tmp\\", 1024*1024*5);

Map paramMap = fileUpload.getParamMap();

Map fileMap = fileUpload.getParamAfterUpload();

String paramValue = (String)paramMap.get("age");
String newFileName = (String)fileMap.get("upFile");

%>
<%=paramValue %><br>
<%=newFileName %>
</body>
</html>



============== FileUpload.java ==========================================
package upload;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * ex)
 * FileUploader fileUploader = new FileUploader(request, "C:\\", 1024*1024*3);
 * Map fileMap = fileUploader.getParamAfterUpload();
 *
 */
public class FileUpload {
 
 private HttpServletRequest request = null;
 private File uploadDir = null;
 private List items = null;
 private Map paramMap = null;
 private long requestLimit = 100*1024*1024; //한번에 업로드 용량은 기본 100메가
 private long fileLimit = 5*1024*1024;  //업로드 가능한 파일의 용량은 기본 5메가
 
 public FileUpload(HttpServletRequest request, String uploadDir) throws Exception{
  this.request = request;
  this.uploadDir = new File(uploadDir);
 
  init();
 }
 
 public FileUpload(HttpServletRequest request, File uploadDir) throws Exception{
  this.request = request;
  this.uploadDir = uploadDir;
 
  init();
 }
 
 public FileUpload(HttpServletRequest request, String uploadDir, long fileLimit) throws Exception{
  this.request = request;
  this.uploadDir = new File(uploadDir);
  this.fileLimit = fileLimit;
  init();
 }
 
 public FileUpload(HttpServletRequest request, File uploadDir, long fileLimit) throws Exception{
  this.request = request;
  this.uploadDir = uploadDir;
  this.fileLimit = fileLimit;
  init();
 }
 
 //초기화 함수
 private void init() throws Exception{
 
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  if(!isMultipart){
   throw new Exception("form의 enctype을 multipart/form-data로 하세요...");
  }
 
  //임시저장공간 생성
  DiskFileItemFactory factory = new DiskFileItemFactory();
  factory.setSizeThreshold(1024);  //메모리에 저장할 최대 size
  factory.setRepository(uploadDir); //임시 저장할 위치
 
  //업로드 핸들러 생성
  ServletFileUpload upload = new ServletFileUpload(factory);
  upload.setSizeMax(requestLimit);  //Set overall request size constraint
 
  items = upload.parseRequest(request); //Parse the request
 
  //파람값들을 맵에 셋팅
  processFormField(items);

 }
 
 //폼의 필드값을 map에 저장한다.
 private void processFormField(List items) throws Exception{
  paramMap = new HashMap();
  Iterator iter = items.iterator();
  while (iter.hasNext()) {
   FileItem item = (FileItem) iter.next();
 
   if (item.isFormField()) {
    paramMap.put(item.getFieldName(), item.getString());
   }
  }
 }
 
 //하나의 파일사이즈를 체크한다.
 private void chkFileLimit() throws Exception{
  Iterator iter = items.iterator();
  while (iter.hasNext()) {
   FileItem item = (FileItem) iter.next();
   if (!item.isFormField()) {
    String fileName = new File(item.getName()).getName();
    long fileSize = item.getSize();
    if(fileName != null && !"".equals(fileName)){
     if(fileLimit<fileSize){
      throw new Exception(fileName+" 파일이 " + fileLimit/1024/1024 + "M를 초과하였습니다.\n");
     }
    }
   }
  }
 }
 
 
 /**
  * request상의 모든파일을 업로드한다.<br>
  * 파일명의 중복을 피하기 위해 중복될경우 파일명 뒤에 '0'을 붙여 업로드한다.<br>
  * 업로드후 변경된 파일명과 param들을 map으로 리턴받아 처리한다.
  * @throws Exception
  */
 public Map getParamAfterUpload() throws Exception{
 
  boolean writeToFile = true; //파일에 쓸것인지 구분 플래그
  Iterator iter = items.iterator();

  chkFileLimit(); //파일들의 사이즈 체크
 
  while (iter.hasNext()) {
   FileItem item = (FileItem) iter.next();
   //Process a file upload
   if (!item.isFormField()) {
       String filePath = item.getName();
       File file = new File(filePath);
       String fileName = file.getName();
      
       if(fileName != null && !"".equals(fileName)){
        //파일업로드시...
        if (writeToFile) {
         String updFilePath = uploadDir+"\\"+fileName;
         String newFilePath = getNewFilePath(updFilePath); //동일한 파일명으로 업로드 될수 있기때문에 파일명이 같을경우 파일명 뒤에 '0'을 붙여 업로드한다.
         File newFile = new File(newFilePath);
         paramMap.put(item.getFieldName(), newFile.getName()); //새로운 파일명을 리턴헤주기 위해 맵에 담는다.
         item.write(newFile);        //파일을 쓴다.
        }
       
        //파일업로드가 아닌  다른출력방식을 사용하고 싶을때...
        /*
        else {
         InputStream uploadedStream = item.getInputStream();
         uploadedStream.close();
        }
         */
       }
   }
  }
  return paramMap;
 }
 
 //새로운 파일명을 생성한다.
 private String getNewFilePath(String filePath){
 
  File file = new File(filePath);
  String sDir = file.getParent();
  File dir = new File(sDir);
  File[] files = dir.listFiles();
 
  for(int i=0; i<files.length; i++){
   String alreadyPath = files[i].getPath();
   if(filePath.equals(alreadyPath)){
    filePath = filePath + "0";
   }
  }
 
  return filePath;
 }
 
 /**
  * request상의 param들을 map으로 반환한다.
  * @return Map
  */
 public Map getParamMap(){
  return paramMap;
 }
 
}


=======================DownloadServlet.java================================
/*
<a href="/Centext/Download?fileName=<%=article.getFilename()%>"><%
 =article.getFilename()%></a>
*/


package upload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @web.servlet name="Download"
 *     display-name="File Download Servlet"
 *    
 * @web.servlet-mapping url-pattern="/Download"
 */
public class DownloadServlet extends HttpServlet {

 protected void performTask(
  javax.servlet.http.HttpServletRequest request,
  javax.servlet.http.HttpServletResponse response)
  throws Exception {


  String fileName = request.getParameter("fileName");


  try {
   String rootPath = getServletConfig().getServletContext().getRealPath("/");
   //String rootPath = request.getRealPath("/");
   String filePath =
    rootPath + "tmp" + File.separator + fileName;
   java.io.File tempFile = new java.io.File(filePath);

   fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
   fileName = BoardUtils.kscToasc(fileName);

   int filesize = (int) tempFile.length();
   String filetype = "application/x-zip-compressed";
   //String fileExt  = fileName.substring(fileName.lastIndexOf(".")+1);  

   String agentType = request.getHeader("Accept-Encoding");

   try {
    if (!tempFile.exists() || !tempFile.canRead()) {
     PrintWriter out = response.getWriter();
     out.println(
      "<script>alert('File Not Found');history.back();</script>");
     return;
    }
   } catch (Exception e) {
    PrintWriter out = response.getWriter();
    out.println(
     "<script>alert('File Not Found');history.back();</script>");
    return;
   }

   boolean flag = false;
   if (agentType != null && agentType.indexOf("gzip") >= 0)
    flag = true;

   flag = false;

   if (flag) {
    response.setHeader("Content-Encoding", "gzip");
    response.setHeader(
     "Content-disposition",
     "attachment;filename=" + fileName);
    javax.servlet.ServletOutputStream servletoutputstream =
     response.getOutputStream();
    java.util.zip.GZIPOutputStream gzipoutputstream =
     new java.util.zip.GZIPOutputStream(servletoutputstream);
    dumpFile(tempFile, gzipoutputstream);
    gzipoutputstream.close();
    servletoutputstream.close();
   } else {
    response.setContentType("application/octet-stream");
    response.setHeader(
     "Content-disposition",
     "attachment;filename=" + fileName);
    javax.servlet.ServletOutputStream servletoutputstream1 =
     response.getOutputStream();
    dumpFile(tempFile, servletoutputstream1);
    servletoutputstream1.flush();
    servletoutputstream1.close();
   }

  } catch (Exception e) {
   PrintWriter out = response.getWriter();

   out.println(
    "<script>alert('File Not Found');history.back();</script>");
   return;
  }

  return;
 }

 private void dumpFile(File realFile, OutputStream outputstream) {
  byte readByte[] = new byte[4096];
  try {
   BufferedInputStream bufferedinputstream =
    new BufferedInputStream(new FileInputStream(realFile));
   int i;
   while ((i = bufferedinputstream.read(readByte, 0, 4096)) != -1)
    outputstream.write(readByte, 0, i);
   bufferedinputstream.close();
  } catch (Exception _ex) {
  }
 }
 /**
  * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  */
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException {
  doPost(req, resp);
 }

 /**
  * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  */
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException {
  try {
   performTask(req, resp);
  } catch (Exception e) {
   throw new ServletException(e.getMessage());
  }
 }

}
============================== BoardUtils.java =======================
package upload;

import java.io.UnsupportedEncodingException;

public class BoardUtils {

 public static String convertHtmlBr(String comment) {
  //**********************************************************************
  if (comment == null)
   return "";
  int length = comment.length();
  StringBuffer buffer = new StringBuffer();
  for (int i = 0; i < length; i++) {
   String tmp = comment.substring(i, i + 1);
   if ("\r".compareTo(tmp) == 0) {
    tmp = comment.substring(++i, i + 1);
    if ("\n".compareTo(tmp) == 0)
     buffer.append("<br>\r");
    else
     buffer.append("\r");
   }
   buffer.append(tmp);
  }
  return buffer.toString();
 }

 public static String ascToksc(String str, boolean isEncode)
  throws UnsupportedEncodingException {
  String result = str;
  if (result == null || result == "")
   return null;

  return new String(result.getBytes("8859_1"), "KSC5601");
 }

 public static String kscToasc(String str)
  throws UnsupportedEncodingException {
  if (str == null || str == "")
   return null;
  return new String(str.getBytes("KSC5601"), "8859_1");
 }

}

출처 : http://blog.naver.com/kwonhjae?Redirect=Log&logNo=30017924746
        : 스트러츠 워크북(한빛 출판사) chapter4 예제 일부

top

Trackback Address :: http://www.ssial.com/trackback/29 관련글 쓰기

Write a comment