반응형

DownloadView 클래스

public class DownloadView extends AbstractView {
    private static final String ENCODING = StandardCharsets.UTF_8.name();

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
        String url = (String) model.get("url");
        String fileName = (String) model.get("fileName");

        HttpURLConnection connection = null;

        try {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + getFileName(request, fileName) + "\";");

            connection = (HttpURLConnection) new URL(url).openConnection();

            response.setContentLengthLong(connection.getContentLengthLong());
            response.setContentType(connection.getContentType());

            FileCopyUtils.copy(connection.getInputStream(), response.getOutputStream());
        } catch (Exception e) {
            throw new IllegalStateException(e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private String getFileName(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        String userAgent = request.getHeader("User-Agent");

        boolean ie = userAgent.contains("MSIE");

        fileName = (ie) ? URLEncoder.encode(fileName, ENCODING) : new String(fileName.getBytes(ENCODING), CharEncoding.ISO_8859_1);

        return fileName;
    }
}

AppConfig 클래스

@Configuration
public class AppConfig {
    @Bean
    public DownloadView downloadView() {
        return new DownloadView();
    }

    @Bean
    public BeanNameViewResolver viewResolver() {
        return new BeanNameViewResolver();
    }
}

DownloadController 클래스

@RestController
public class DownloadController {
    @RequestMapping("/download")
    public ModelAndView download(String url, String fileName) {
        return new ModelAndView("downloadView")
                .addObject("url", url)
                .addObject("fileName", fileName);
    }
}

Download 테스트

반응형

'Development > Spring' 카테고리의 다른 글

[Spring] BeanFactory & ApplicationContext  (0) 2020.12.27
[Spring] Paging  (0) 2020.12.27
[Spring] Spock Test  (0) 2020.12.27
[Spring] Controller  (0) 2020.12.27
[Spring] Spring Boot 프로젝트 세팅  (0) 2020.12.27

+ Recent posts