728x90
디자인
<div class="form-row">
<div class="form-group col-6">
<label>파일 다운로드</label>
<div class="filebox">
<input id="upload-name" class="uploadbox d-inline-block" placeholder="파일 경로" readonly>
<label for="uploadFile" class="d-inline-block cursor">파일 열기</label>
<input type="file" id="uploadFile" name="uploadFile">
<div id="attachFile"></div>
</div>
<!-- 파일업로드 input에 파일경로를 등록 -->
<script>
$("#uploadFile").on('change',function(){
var fileName = $("#uploadFile").val();
$("#upload-name").val(fileName);
});
</script>
</div>
</div>
function downloadFile(seq){
fileDownloadIframe.location.href = "<c:url value='/oper/file/downloadFile.do'/>?seq="+seq;
}
/**
* 템플릿 파일을 다운로드한다.
* @param paramMap - HashMap
* @return "jsonView"
* @exception Exception
*/
@RequestMapping(value = "/oper/file/templateFileDownload.do", method = RequestMethod.POST)
@ResponseBody
public ModelAndView templateFileDownload(
@ModelAttribute("searchVO") SearchVO pSearchVO,
@RequestParam HashMap<String ,Object> paramMap,
ModelAndView mv, HttpServletRequest request) throws Exception {
String tmpFileNm = (String) paramMap.get("tmpFileNm");
String tempPath = request.getSession().getServletContext().getRealPath("/WEB-INF/templete");
sFullPath = tempPath + File.separator + tmpFileNm;
File file = FileUtil.getPathTraversalFile("", FilenameUtils.getFullPath(sFullPath), FileUtil.getName(sFullPath));
mv.addObject("file", file);
mv.addObject("fileNm", tmpFileNm);
mv.setViewName("downloadView");
return mv;
}
dispatcher-servlet.xml 에 빈 등록
<!-- download view -->
<bean id="downloadView" class="test.cmmn.down.DownloadView"/>
AbstractView의 메소드 중 renderMergedOutputModel()을 쓰면 된다.
컨트롤러에서 AbstractView를 상속한 클래스를 호출하면
renderMergedOutputModel()를 호출해서 기능을 수행한다.
매개변수로 HttpServletRequest request, HttpServletResponse response가 있기 때문에 왠만한 전달값은
전부 받을 수 있을 것 같다
package test.cmmn.down;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;
import test.cmmn.util.EgovClntInfo;
public class DownloadView extends AbstractView{
private final static Logger LOGGER = LoggerFactory.getLogger(DownloadView.class);
@Override
protected void renderMergedOutputModel(Map<String, Object> map,
HttpServletRequest request, HttpServletResponse response) throws Exception {
File file = (File)map.get("file"); // 서버에 존재하는 실제 파일
String fileNm = (String)map.get("fileNm"); // 원하는 파일명
int fSize = 0;
if(file != null) {
fSize = (int)file.length();
}
if (file != null && !(" ").equals(file.getName()) && fSize > 0) {
String fileName = (file != null) ? file.getName() : "";
response.setContentType(this.getContentType());
response.setContentLength((int)file.length());
// if(request.getParameter("direct") != null && request.getParameter("direct").equals("direct")){ view jsp화면에서 form태그안에 input type=hidden name="direct"
if(map.get("direct") != null && map.get("direct").equals("direct")){
int lastIndexUnder = fileName.lastIndexOf("_");
int lastIndexDot = fileName.lastIndexOf(".");
fileName = fileName.substring(0, lastIndexUnder) + fileName.substring(lastIndexDot);
//response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8") + ";");
//resp.setHeader("Content-disposition","attachment; filename="+fileName); // 파일명 셋팅
if(fileNm != null && !("").equals(fileNm)){
EgovClntInfo.setDisposition(fileNm, request, response);
}else{
EgovClntInfo.setDisposition(fileName, request, response);
}
}else{
//response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8") + ";");
//resp.setHeader("Content-disposition","attachment; filename="+fileName); // 파일명 셋팅
if(fileNm != null && !("").equals(fileNm)){
EgovClntInfo.setDisposition(fileNm, request, response);
}else{
EgovClntInfo.setDisposition(fileName, request, response);
}
}
response.setHeader("Content-Transfer", "binary");
//ajax
//response.setHeader("Set-Cookie", "fileDownload=true;path=/; HttpOnly");
OutputStream out = response.getOutputStream();
FileInputStream fis = null;
try{
fis = new FileInputStream(file);
FileCopyUtils.copy(fis, out);
} catch (IOException e) {
LOGGER.error(e.getMessage());
} catch(Exception e){
throw e;
}finally{
if(fis != null){
try{ fis.close(); }catch(IOException e){LOGGER.error(e.getMessage());} catch(Exception e){ LOGGER.error(e.getMessage());}
}
}
out.flush();
}else{
response.setContentType("text/html;charset=utf-8");
PrintWriter output = response.getWriter();
output.println("<script type='text/javascript' >");
//output.println("alert('파일정보를 확인할 수 없습니다.');");
output.println("alert('NO FILE');");
//output.println("history.go(-1);");
output.println("</script>");
output.flush();
output.close();
}
}
}
제이쿼리 파일 다운로드
$('#btnDownloadYearRcvpay').click(function(){
var row = $("#dg_day").datagrid("getSelected");
g_url = "<c:url value='/aaabbbbdo'/>?tmpFileNm=ddsfsdf.xlsx&searchDate="+row.date;
g_msg = "다운로드하시겠습니까?";
if (confirm(g_msg)){
//$.messager.progress({msg:"Processing..."}); // display the progress bar
$.fileDownload(g_url, {
successCallback: function(url){
$.messager.progress('close'); // hide progress bar
},
failCallback: function(html, url){
//alert('template file download failed');
$.messager.progress('close'); // hide progress bar
}
});
}
});
$.fileDownload($("#searchForm").prop('action'),{
httpMethod: "POST",
data:$("#searchForm").serialize(),
successCallback: function (url) {
$("#commonLoader").hide();
},
failCallback: function(responesHtml, url) {
$("#commonLoader").hide();
alert('관리자에게 문의 주세요.');
}
});
728x90