티스토리 뷰

Programming/Java

Spring MVC : 파일 다운로드

파란크리스마스 2022. 6. 6. 16:26
728x90

Spring MVC : 파일 다운로드

package com.bluexmas.ui.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

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

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bluexmas.util.ConfigUtils;
import com.bluexmas.util.FileUtilsEx;

@Controller
public class ExcelDownloadController {

  private static final Logger logger = LoggerFactory.getLogger(CommonAcountController.class);

  private static final int COMPRESSION_LEVEL = 3;

  private static final int BUFFER_SIZE = 1024 * 2;

  @RequestMapping(value = { "/app/download.do", "/{app}/app/download.do" })
  public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    // 다운로드 파일명 설정
    this.setDownloadFilename("bluexmas.png", request, response);
    
    InputStream is = null;
    BufferedInputStream fin = null;
    BufferedOutputStream outs = null;

    try {
      File sourceFile = new File(ConfigUtils.getConfigPath(), "bluexmas.png");
      is = new FileInputStream(sourceFile);
      fin = new BufferedInputStream(is);
      outs = new BufferedOutputStream(response.getOutputStream());
      int read = 0;
      
      byte[] buffer = new byte[BUFFER_SIZE];
      while ((read = fin.read(buffer)) != -1) {
        outs.write(buffer, 0, read);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (outs != null) outs.close();
      if (fin != null) fin.close();
      if (is != null) is.close();
    }
  }

  @RequestMapping(value = { "/app/zip_download.do", "/{app}/app/zip_download.do" })
  public void zip_download(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //
    ZipArchiveOutputStream zos = null;
    
    try {
      zos = new ZipArchiveOutputStream(response.getOutputStream());
      zos.setEncoding("UTF-8");
      zos.setLevel(COMPRESSION_LEVEL); // 압축 레벨 - 최대 압축률은 9, 디폴트 8
      
      String zipName = FileUtilsEx.cleanDirName("bluexmas.zip");
      this.setDownloadFilename(zipName, request, response);
      
      File sourceFile = new File(ConfigUtils.getConfigPath(), "bluexmas.png");
      this.compress(zos, sourceFile, "santa.png");
      
      zos.finish();
      int file_size = (int) zos.getBytesWritten();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }

  // 압축파일에 파일 주가
  private void compress(ZipArchiveOutputStream zos, File sourceFile, String zipName) throws IOException {
    BufferedInputStream bis = null;

    try {
      bis = new BufferedInputStream(new FileInputStream(sourceFile));
      ZipArchiveEntry zentry = new ZipArchiveEntry(zipName);
      
      if (sourceFile != null)
        zentry.setTime(sourceFile.lastModified());
      
      zos.putArchiveEntry(zentry);

      byte[] buffer = new byte[BUFFER_SIZE];
      int cnt = 0;
      while ((cnt = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
        zos.write(buffer, 0, cnt);
      }
      zos.closeArchiveEntry();

    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    } finally {
      if (bis != null) {
        bis.close();
      }
    }
  }

  // 다운로드 파일명 설정
  private void setDownloadFilename(String fileName, HttpServletRequest request, HttpServletResponse response)
      throws UnsupportedEncodingException {
    String header = getBrowser(request);
    if (header.contains("MSIE")) {
      String docName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
      response.setHeader("Filename-Encoding", "urlencode");
      response.setHeader("Content-Disposition", "attachment;filename=" + docName + ";");
    } else if (header.contains("Firefox")) {
      String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
      response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");
    } else if (header.contains("Opera")) {
      String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
      response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");
    } else if (header.contains("Chrome")) {
      String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
      response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");
    }
    response.setHeader("Content-Type", "application/octet-stream");
    response.setHeader("Content-Transfer-Encoding", "binary;");
    response.setHeader("Pragma", "no-cache;");
    response.setHeader("Expires", "-1;");
    // response.setHeader("filesize", file_size+";");
    response.setHeader("dn_filename", URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"));
  }

  // 브라우져 확인
  private String getBrowser(HttpServletRequest request) {
    String header = request.getHeader("User-Agent");
    if (header.contains("MSIE") || header.contains("Trident") || header.contains("Dalvik")) {
      return "MSIE";
    } else if (header.contains("Chrome")) {
      return "Chrome";
    } else if (header.contains("Opera")) {
      return "Opera";
    }
    return "Firefox";
  }

}
댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함