본문 바로가기

IT

[스프링 강좌] 파일 다운로드 처리 소스

반응형

원래파일명하고 물리파일명을 받아
물리파일명을 읽어 원래 파일명으로 다운로드 시킵니다.

@RequestMapping("/download")
      public void download(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
           
        
       int fileNo = (request.getParameter("fileNo")==null)?0:Integer.parseInt(request.getParameter("fileNo"));
        
       Map<String,String> fileInfo = portalService.getPortalBoardFileInfo(fileNo);
           
          String filename = fileInfo.get("ORG_NAME");
          String downname = fileInfo.get("SYS_NAME");
          String path = fileInfo.get("PATH");
           
           
          String realPath = "";
          System.out.println("downname: "+downname);
          if (filename == null || "".equals(filename)) {
              filename = downname;
          }
            
          try {
              String browser = request.getHeader("User-Agent"); 
 
              if (browser.contains("MSIE") || browser.contains("Trident")
                      || browser.contains("Chrome")) {
                  filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+",
                          "%20");
              } else {
                  filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
              }
          } catch (UnsupportedEncodingException ex) {
              System.out.println("UnsupportedEncodingException");
          }
          realPath = path +"/" + downname;
          System.out.println(realPath);
          File file1 = new File(realPath);
          if (!file1.exists()) {
              return ;
          }
                
          response.setContentType("application/octer-stream");
          response.setHeader("Content-Transfer-Encoding", "binary;");
          response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
          try {
              OutputStream os = response.getOutputStream();
              FileInputStream fis = new FileInputStream(realPath);
    
              int ncount = 0;
              byte[] bytes = new byte[512];
    
              while ((ncount = fis.read(bytes)) != -1 ) {
                  os.write(bytes, 0, ncount);
              }
              fis.close();
              os.close();
          } catch (FileNotFoundException ex) {
              System.out.println("FileNotFoundException");
          } catch (IOException ex) {
              System.out.println("IOException");
          }
      }
반응형