본문 바로가기
java

file upload file download.. 파일 업로드 다운 로드 서블릿

by 새로운 도전을 위한 한걸음 2015. 5. 10.

파일 업로드 다운로드 처리 ..

 

파일 업로드  common.fileupload 1.2 버전..

 

 

 

package com.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.*;

 

 public class AttachDown extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
 
 public AttachDown() {
  super();
 }    
 

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
 }   
 

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  System.out.println("request.getCharacterEncoding() " + request.getCharacterEncoding());
  //request.setCharacterEncoding("EUC-KR");
  //request.setCharacterEncoding("euc-kr");
  String fileName = request.getParameter("fileName");
  HttpSession sess= request.getSession();
  String filePathsss = sess.getServletContext().getRealPath("/download/");
  
  // String filePath = request.getRealPath("/")+"/down/";  // ROOT 경로 + 위치
   //System.out.println(filePath);
  
  String filePath =request.getParameter("filePath");
   //응답 헤더의 Content-Type을 세팅한다.
  response.setContentType("application/octet-stream");
   //response.setContentType("application/x-msdownload");
  
   System.out.println("filePathsss   ==  [[" +filePathsss+"     ]] ==") ;
  
  
   System.out.println("fileName   [[ " +fileName+ "          ]]   filePath    [[  "  + filePath +"]]");
  
   //Content-Disposition 세팅하기위해 file 이름을 변환한다.
 
  // String convName1 = new String(fileName .getBytes("EUC-KR"), "8859_1");
   String convName= java.net.URLEncoder.encode(fileName,"UTF8");

   response.setHeader("Content-Disposition", "attachment;filename=\"" + convName + "\";");
  
  
   // 폴더에 있는 파일 가져오기 위해 다른 방법으로 변환
  
   File file = new File(filePath,fileName);


   // 사용자에게 보내주기 위해 스트림객체 생성
   byte b[] = new byte[5 * 1024 * 1024];   
      if (file.length() > 0 && file.isFile()) // 0byte이상이고, 해당 파일이 존재할 경우
   {
    BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file)); // 인풋객체생성
    BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream()); // 응답객체생성
  
    
    int read = 0;
    try {
     while ((read = fin.read(b)) != -1){
         outs.write(b,0,read);
     }
     outs.close();
     fin.close();
    } catch (Exception e) {
     System.out.println("download error : " + e.getMessage());
    } finally {
     if(outs!=null) outs.close();
     if(fin!=null) fin.close();

    }

   }

 }          
}

 

 

package com.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;


public class UploadServlet extends HttpServlet {
   
    String upload_dir = null;
    public void init(ServletConfig config) throws ServletException {
          super.init(config); 
          upload_dir = "c:/zzz/";
    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   

        // form type이 multipart/form-data 면 true 그렇지 않으면 false를 반환
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       
        if (isMultipart) {
            try {

             
                long yourMaxRequestSize = 1024 * 1024 * 10;   //업로드 최대 사이즈 설정 (100M)

                System.out.println("==============================================================");
               
                FileItemFactory factory = new DiskFileItemFactory();
            
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(yourMaxRequestSize);          // 임시 업로드 디렉토리 설정
                upload.setHeaderEncoding("EUC_KR");               // 인코딩 설정
               
               
               
                System.out.println("==============================================================");
                System.out.println("factory   [  " + factory+ "    ]]");
                System.out.println("==============================================================");
                System.out.println("upload   [  " + upload+ "    ]]");
                System.out.println("==============================================================");
               
               

                /**

                 *  업로드 진행 상태 출력 (Watching progress)

                */
                ProgressListener progressListener = new ProgressListener(){
                   private long megaBytes = -1;
                   public void update(long pBytesRead, long pContentLength, int pItems) {
                       long mBytes = pBytesRead / 4000;
                       if (megaBytes == mBytes) {
                           return;
                       }
                       megaBytes = mBytes;
                       System.out.println("We are currently reading item " + pItems);
                       if (pContentLength == -1) {
                           System.out.println("So far, " + pBytesRead + " bytes have been read.");
                       } else {
                           System.out.println("So far, " + pBytesRead + " of " + pContentLength
                                              + " bytes have been read.");
                       }
                   }
                };
                upload.setProgressListener(progressListener);   // 진행상태 리스너 추가
   

                String fieldName = null;
                String fieldValue = null;
                String fileName = null;
                String contentType = null;
                long sizeInBytes = 0;

                List items = upload.parseRequest(request);               
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                   
                    // 정상적인 폼값 출력 및 처리
                    if (item.isFormField()) {
                        fieldName = item.getFieldName();
                        fieldValue = item.getString();
                       
                        System.out.println("-----+-----+-----+-----+--sdsfdssf---+-----+-----+-----");
                        System.out.println("Field Name : "+fieldName);
                        System.out.println("Field Value : "+fieldValue);
                        System.out.println("-----+-----+-----+---cxcxcxcx--+-----+-----+-----+-----");
                       

                    // 업로드 파일 처리
                    } else {
                  
                        fieldName = item.getFieldName();
                        String fileFullName = item.getName(); // 로컬 pc의 경로포함해서의 이름.
                        contentType = item.getContentType();
                        sizeInBytes = item.getSize();
                       
                        String saveFile = FilenameUtils.getName(fileFullName);
                       
                        File uploadFile = new File(upload_dir+saveFile);
                        item.write(uploadFile);
                       
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                        System.out.println("Field Name : "+fieldName);
                        System.out.println("File Name : "+fileName);
                        System.out.println("ContentType : "+contentType);
                        System.out.println("File Size : "+sizeInBytes);
                        System.out.println("-----+-----+-----+-----+-----+-----+-----+-----");
                            
                       
                    }
                }

 

            // 설정한 업로드 사이즈 초과시 exception 처리
            } catch (SizeLimitExceededException e) {
                e.printStackTrace();   

            // 업로드시 io등 이상 exception 처리
            } catch (FileUploadException e) {
                e.printStackTrace();

            // 기타 exception 처리
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }   
}