java file download

JooKit 주킷 2021. 11. 15. 21:48
목차 접기
728x90
반응형
String filePath = "filePath";
        String fileName = file1 + ".txt";

        String fileNameOrg = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

        try{                                        
            request.setCharacterEncoding("UTF-8");
            fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
            File file = new File(filePath, fileName);

            if(file.isFile()){
                int bytes = (int)file.length();
                String header = request.getHeader("User-Agent");

                if (header.contains("MSIE") || header.contains("Trident")) {
                    fileNameOrg = URLEncoder.encode(fileNameOrg,"UTF-8").replaceAll("\\+", "%20");
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileNameOrg + ";");
                } else {
                    fileNameOrg = new String(fileNameOrg.getBytes("UTF-8"), "ISO-8859-1");
                   response.setHeader("Content-Disposition", "attachment; filename=\"" + fileNameOrg + "\"");
                }

                response.setContentType( "application/download; UTF-8" );
                response.setContentLength(bytes);
                response.setHeader("Content-Type", "application/octet-stream");                
                response.setHeader("Content-Transfer-Encoding", "binary;");
                response.setHeader("Pragma", "no-cache;");
                response.setHeader("Expires", "-1;");

                BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());

                byte[] readByte = new byte[4096];
                try{
                    while((bytes = fin.read(readByte)) > 0){
                        outs.write(readByte, 0, bytes);
                        outs.flush();
                    }
                }
                catch(Exception e){
                    e.printStackTrace();
                }
                finally{
                    outs.close();
                    fin.close();
                }
            } else {
                response.setCharacterEncoding("UTF-8"); 
                response.setContentType("text/html; charset=UTF-8");

                PrintWriter out = response.getWriter();
                out.println("파일이 존재하지 않습니다.");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
728x90
반응형
LIST