package spring.download;
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 {
File file = (File) model.get("downloadFile"); // 모델데이터중 downloadFile이라는 이름으로 전달된 모델을 가져와서 파일객체로 변환
response.setContentType(getContentType()); // 타입설정
response.setContentLength((int) file.length()); // 다운로드되는 파일의 크기 설정
String userAgent = request.getHeader("User-Agent");
boolean ie = userAgent.indexOf("MSIE") > -1; // 이게 익스플로?는 다르게해야되서 분리하기 위함임
String fileName = null;
if (ie) {
fileName = URLEncoder.encode(file.getName(), "utf-8");
} else {
fileName = new String(file.getName().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 ex) {
}
}
out.flush();
}
}
package spring.controller;
import java.io.File;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class DownloadController implements ApplicationContextAware {
private WebApplicationContext context = null;
@RequestMapping("/download.do")
public ModelAndView download(String name) throws Exception {
System.out.println("ddsdadsf");
File downloadFile = getFile(name);
return new ModelAndView("download", "downloadFile", downloadFile); // 뷰이름, 모델데이터명, 값
}
private File getFile(String name) {
String path = "D:\\신경오\\"+name;
return new File(path);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = (WebApplicationContext) applicationContext;
}
}