본문 바로가기
IT 개발/JAVA

브라우저 확인 후 파일 다운로드

by Love of fate 2021. 9. 23.
728x90
반응형

[브라우저 확인 후 파일 다운로드]

 

- 브라우저 별로 한글 인코딩 필요 --> 한글 깨짐 방지

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
    @RequestMapping(value="/info/downloadManual.do")
    public void downloadManual(HttpServletRequest request, HttpServletResponse response) {
        String path = "파일경로"//full경로, 추후 모딩 필요
        String fileName = ""//파일명
 
        File file = new File(path);
 
        FileInputStream fileInputStream = null;
        ServletOutputStream servletOutputStream = null;
 
        try{
            String downName = null;
            String browser = request.getHeader("User-Agent");
            //파일 인코딩
            if(browser.contains("MSIE"|| browser.contains("Trident"|| browser.contains("Chrome")){//브라우저 확인 파일명 encode
                downName = URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+""%20");
            }else{
                downName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
 
            response.setHeader("Content-Disposition","attachment;filename=\"" + downName+"\"");
            response.setContentType("application/octer-stream");
            response.setHeader("Content-Transfer-Encoding""binary;");
 
            fileInputStream = new FileInputStream(file);
            servletOutputStream = response.getOutputStream();
 
            byte b [] = new byte[1024];
            int data = 0;
            while((data=(fileInputStream.read(b, 0, b.length))) != -1){
                servletOutputStream.write(b, 0, data);
            }
            servletOutputStream.flush();//출력
 
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(servletOutputStream!=null){
                try{
                    servletOutputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(fileInputStream!=null){
                try{
                    fileInputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
 
cs
728x90
반응형