From 5dcaea783e06b1bf7e867d682b54087639b6d5c6 Mon Sep 17 00:00:00 2001 From: mjkhan21 Date: Thu, 25 Apr 2024 17:11:02 +0900 Subject: [PATCH] =?UTF-8?q?DownloadView=20=EC=9D=B4=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cokr/xit/foundation/web/DownloadView.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/cokr/xit/foundation/web/DownloadView.java diff --git a/src/main/java/cokr/xit/foundation/web/DownloadView.java b/src/main/java/cokr/xit/foundation/web/DownloadView.java new file mode 100644 index 0000000..cf0dc92 --- /dev/null +++ b/src/main/java/cokr/xit/foundation/web/DownloadView.java @@ -0,0 +1,52 @@ +package cokr.xit.foundation.web; + +import java.net.URLEncoder; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.view.AbstractView; + +import cokr.xit.foundation.Assert; +import cokr.xit.foundation.Downloadable; + +/**파일의 다운로드를 처리하기 위한 {@link org.springframework.web.servlet.View} + *

DownloadView가 파일을 다운로드하기 위해서는 {@link org.springframework.web.servlet.ModelAndView}로 다음과 같은 속성의 값을 지정해야 한다. + *

+ * @author mjkhan + */ +public class DownloadView extends AbstractView { + public static String getFilename(Map model) { + Object obj = model.get("download"); + if (obj instanceof Downloadable) { + Downloadable downloadable = (Downloadable)obj; + return downloadable.getFilename(); + } + return null; + } + + @Override + protected void renderMergedOutputModel(Map model, HttpServletRequest hreq, HttpServletResponse hresp) throws Exception { + Downloadable downloadable = (Downloadable)model.get("download"); + if (downloadable == null) { + hresp.setStatus(HttpServletResponse.SC_NOT_FOUND); + hresp.sendError(HttpServletResponse.SC_NOT_FOUND); + return; + } + String filename = downloadable.getFilename(); + if (Assert.isEmpty(filename)) + throw new IllegalArgumentException("Unable to determine the filename"); + + String charset = downloadable.getCharset(); + hresp.setCharacterEncoding(charset); + hresp.setContentType(downloadable.getContentType()); + hresp.setHeader("Content-Disposition", downloadable.getDisposition() + "; filename=\"" + URLEncoder.encode(filename, charset) +"\""); + Long length = downloadable.getLength(); + if (length != null) + hresp.setContentLengthLong(length.longValue()); + + downloadable.write(hresp.getOutputStream()); + } +} \ No newline at end of file