본문 바로가기
컴퓨터관련

spring을 이용하여 File download 하기

by 기록이답이다 2016. 1. 20.
반응형
spring project에서 file download를 구현할 필요가 생겼음 아래와 같은 방법으로 처리하였음
  • web-servlet.xml
	<bean id="downloadViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver">
		<property name="order">
			<value>0</value>
		</property>
	</bean>
		
	<!-- 파일다운로드 담당하는 뷰클래스 -->
	<bean id="downloadView" class="com.ictee.group.common.DownloadView" />
	<bean id="zipdownloadView" class="com.ictee.group.common.ZipDownloadView" />
   
  • file download link
			<!--첨부파일-->
			<div class="box b_bg quickTitle" style="padding:10px; margin-top:10px;">
				<p><span class="b">첨부파일</span>&nbsp;(<span class="b02">${fileList.size()}개</span>) <a href="/zipDown.do?atchFileGroupNo=${atchFileGroupNo}">[모두받기]</a>
<%-- 				<c:if test="${atchMode eq 'modify'}"><a class="_ATCHDELETE_ apointer" id="g_${atchFileGroupNo}">[삭제]</a></c:if> --%>
				</p>
				<div class="line2" style="margin:8px -10px 9px -10px"></div>
				<ul>
					<c:forEach var="file" items="${fileList}">
						<li style="margin-top:3px; text-align: left;"><img src="../images/common/icon_png1.gif" alt=""><a href="/down.do?atchmnflNo=${file.atchmnflNo}"> ${file.fileNm}<span class="gr s"><script>filesize('${file.fileMg}')</script></span></a>
						<c:if test="${atchMode eq 'modify'}"><a class="_ATCHDELETE_ apointer" id="f_${file.atchmnflNo}"><img src="/images/common/ico_del.gif"/></a></c:if>
						</li>
					</c:forEach>
				</ul>
			</div>
			<!--첨부파일 끝-->
 
  • DownloadController.java
	@RequestMapping("/down.do")
	public ModelAndView down(ModelMap model, HttpServletRequest request, TBBase vo) throws Exception{
		ModelAndView mav = new ModelAndView("downloadView");
		
		Map<String, Object> param = vo.createMap();
		param.put("queryKey", "attach.getAtchFileList");
		ConvertMap fileMap = (ConvertMap) webService.getObject(param);
		
		if(fileMap != null && fileMap.get("oldFileNm") != null && !fileMap.get("oldFileNm").equals("")) {
			if(fileMap.get("fileNm") == null || fileMap.get("fileNm").equals("null")) {
//				mav.setViewName("comm/ajaxStr");
//				mav.addObject("jsonData", "첨부파일이 존재하지 않습니다.");
			} else {
				mav.addObject("path", GroupConst.BASE_UPLOAD_DIR + "/"+fileMap.get("filePath"));
				mav.addObject("fileName", fileMap.get("fileNm"));
				mav.addObject("oldFileName", fileMap.get("oldFileNm"));
				
				param.put("queryKey", "attach.updateDownloadInfo");
				webService.update(param);
			}
		}
		
		return mav;
	}

	@RequestMapping("/zipDown.do")
	public ModelAndView zipdown(ModelMap model, HttpServletRequest request, TBBase vo) throws Exception{
		ModelAndView mav = new ModelAndView("zipdownloadView");

		Map<String, Object> param = vo.createMap();
		param.put("queryKey", "attach.getAtchFileList");
		List<ConvertMap> fileList = webService.list(param);

		String fileStr = "";
		String oldFileStr = "";
		for(ConvertMap m : fileList) {
			if(m.get("fileNm") == null || m.get("fileNm").equals("null")) continue;
			fileStr += m.get("filePath")+"/"+m.get("fileNm")+"?";
			oldFileStr += m.get("filePath")+"/"+m.get("oldFileNm")+"?";
		}

		if(fileStr != null && !fileStr.equals("")) {
			mav.addObject("fileStr", fileStr);
			mav.addObject("oldFileStr", oldFileStr);
			
			param.put("queryKey", "attach.updateDownloadInfo");
			webService.update(param);
		}

		return mav;
	}
 
  • DownloadView.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

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

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;


public class DownloadView extends AbstractView {
	public DownloadView() {
		setContentType("application/download; charset=utf-8");
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,HttpServletRequest request, HttpServletResponse response) throws Exception {
		String _path = (String)model.get("path");
		String _name = (String)model.get("oldFileName");
		
		if(_name == null || _name.equals("")) return;
		File file = new File(_path + "/" + _name );

		response.setContentType(getContentType());
		response.setContentLength((int)file.length());

		String userAgent = request.getHeader("User-Agent");
		boolean ie = userAgent.indexOf("MSIE") > -1;
		String orgFileName = (String)model.get("fileName");
		String fileName = orgFileName;
		

        //파일 인코딩
        if(userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Chrome")){             
        	fileName = URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+", "%20");
        } else {               
        	fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }

		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
		response.setHeader("Content-Transfer-Encoding", "binary");
		OutputStream out = response.getOutputStream();

		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			FileCopyUtils.copy(fis, out);
		} finally {
			if(fis != null) {
				try {
					fis.close();
				} catch(IOException ioe) {}
			}
		}
		out.flush();
	}
}
 
  • ZipDownloadView.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

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.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;


public class ZipDownloadView extends AbstractView {
	public ZipDownloadView() {
		setContentType("application/download; charset=utf-8");
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileStr = (String)model.get("fileStr");
		String oldFileStr = (String)model.get("oldFileStr");
		
		if(oldFileStr == null || oldFileStr.equals("")) return;
		
		String zipFileName = System.nanoTime()+"";
		FileOutputStream fos = new FileOutputStream(GroupConst.BASE_UPLOAD_DIR+"/"+zipFileName+".zip");
		ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);
		zos.setEncoding("UTF-8");
		
		String[] fileStrs = fileStr.split("\\?");
		String[] oldFileStrs = oldFileStr.split("\\?");

		byte[] buff = new byte[4096];
		for(int i=0; i<oldFileStrs.length; i++) {
			File file = new File(GroupConst.BASE_UPLOAD_DIR+"/"+oldFileStrs[i]);
			FileInputStream fis = new FileInputStream(file);
			ZipArchiveEntry ze = new ZipArchiveEntry(fileStrs[i]);
			zos.putArchiveEntry(ze);
			
			int len;
			while((len = fis.read(buff)) > 0) {
				zos.write(buff, 0, len);
			}
			
			zos.closeArchiveEntry();
			fis.close();
		}		
		
		zos.close();
		
		File zipFile = new File(GroupConst.BASE_UPLOAD_DIR+"/"+zipFileName+".zip");
		response.setContentType(getContentType());
		response.setContentLength((int)zipFile.length());

		String userAgent = request.getHeader("User-Agent");
		boolean ie = userAgent.indexOf("MSIE") > -1;
		String fileName = null;

		String orgFileName = "download.zip";
		if(ie) {
			fileName = URLEncoder.encode(orgFileName, "utf-8");
		} else {
			fileName = new String(orgFileName.getBytes("utf-8"), "iso-8859-1");
		}

		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
		response.setHeader("Content-Transfer-Encoding", "binary");
		OutputStream out = response.getOutputStream();

		FileInputStream fis2 = null;
		try {
			fis2 = new FileInputStream(zipFile);
			FileCopyUtils.copy(fis2, out);
		} finally {
			if(fis2 != null) { try { fis2.close(); } catch(IOException ioe) {} }
			zipFile.delete();
		}
		out.flush();
	}
}
 
  • 실행결과

 

 

 

 

반응형