1. context.xml 설정


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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- 모든 경로는 지정한 경로명이 붙으므로 해당 경로를 피하기 위해 업로드 파일들을 resources/ 폴더 아래 넣음 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
        <property name="order" value="1"/>
    </bean>
    
    <!-- BeanNameViewResolver : view 와 동일한 이름을 갖는 bean을 view 객체로 사용
                                custom view 클래스인 UtilFile을 view로 사용해야 하기 때문에 mapping함 -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="0" />
    </bean>
 
    <!--custom view 클래스 -->
    <bean id="downloadView" class="com.cafe24.smart.util.UtilFile"/>
 
</beans>
cs



2. 파일 다운로드 하이퍼링크


1
2
3
4
5
6
7
8
<html>
<head>
    <title>title</title>
</head>
<body>
    <a href="<c:url value='/re/fileDownload?reCode=${reward.reCode}'/>">${reward.reDocument}</a>
</body>
</html>
cs


화면에는 업로드된 파일 경로 전체가 보이는 것처럼 느껴지겠지만 Controller에서 해당 파일명 + 확장자까지만 보이게 잘라놓은 상태이다.

해당 파일명을 클릭하면 /re/fileDownload 경로를 값으로 받는 컨트롤러 메소드로 이동하며 get 방식으로 pk컬럼 값을 받게 된다.



3. 파일을 다운로드 하는 컴포넌트 클래스


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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.cafe24.smart.util;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.view.AbstractView;
 
import com.cafe24.smart.approve.domain.Draft;
import com.cafe24.smart.reward.domain.Reward;
 
//@Component > @Service
//            : 스프링 프레임워크가 관리하는 컴포넌트의 일반적 타입 
//            : 개발자가 직접 조작이 가능한 클래스의 경우 해당 어노테이션을 붙임
//            : ( <=> @Bean : 개발자가 조작이 불가능한 외부 라이브러리를 Bean으로 등록시 사용)
@Component
// AbstractView : 스프링 MVC 사용시 DispatcherServlet 기능
//                : requestURI에 따라 컨트롤러로 분기하고 로직 처리 후 Resolver를 사용하여
//                : 해당 jsp 파일을 찾아 응답하게 되는데 그 사이 시점을 잡아 처리하는 부분의 기능
public class UtilFile extends AbstractView {
//  파일 다운로드
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
        
        setContentType("application/download; charset=utf-8");
        
        File file = (File) model.get("downloadFile");
        
        response.setContentType(getContentType());
        response.setContentLength((int) file.length()); 
        
        String header = request.getHeader("User-Agent");
        boolean b = header.indexOf("MSIE"> -1;
        String fileName = null;
        
        if (b) {
            fileName = URLEncoder.encode(file.getName(), "utf-8");
        } else {
            fileName = new String(file.getName().getBytes("utf-8"), "iso-8859-1");
        }
        
        response.setHeader("Conent-Disposition""attachment); filename=\"" + fileName + "\";");
        response.setHeader("Content-Transter-Encoding""binary");
        
        OutputStream out = response.getOutputStream();
        FileInputStream fis = null;
        
        try {
            fis = new FileInputStream(file);
            
            FileCopyUtils.copy(fis, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            
            out.flush();
        }
    }
}
cs



4. 파일 다운로드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Controller
public class RewardController {
//  파일 다운로드 하는 메소드
    @RequestMapping(value = "/re/fileDownload", method = RequestMethod.GET)
//  get 방식 하이퍼링크 경로로 보낸 PK 값을 인자로 받음
    public ModelAndView reDocumentDown(@RequestParam(value="reCode"int reCode) {
        
//      pk 값으로 해당 도메인 객체의 파일 전체 경로 값을 받은 후
        Reward reward = rewardService.reListByReCodeServ(reCode);
        
//      전체 경로를 인자로 넣어 파일 객체를 생성
        File downFile = new File(reward.getReDocument());
        
        System.out.println("RewardController reDocumentDown reCode : " + reCode);
        
//      생성된 객체 파일과 view들을 인자로 넣어 새 ModelAndView 객체를 생성하며 파일을 다운로드
//      (자동 rendering 해줌)
        return new ModelAndView("downloadView""downloadFile", downFile);
    }
}
cs


+ Recent posts