2014-10-28 2 views
0

사용자가 Excel 파일을 다운로드 할 수있게 해주는 기능을 웹 응용 프로그램에 추가하려고합니다. Java HttpServlet 다운로드 방법 Excel 파일

는 다음 코드와이를 달성하기 위해 노력하고있어 :

@Override 
    public void doPost(HttpServletRequest request, HttpServletResponse response) { 
     File file = new File("d:/test/test.xls"); 
     response.setContentType("application/xls"); 
     response.addHeader("Content-Disposition", "attachment; filename=test.xls"); 
     response.setContentLength((int) file.length()); 

     try { 
      FileInputStream fileInputStream = new FileInputStream(file); 
      OutputStream responseOutputStream = response.getOutputStream(); 
      int bytes; 
      while ((bytes = fileInputStream.read()) != -1) { 
       responseOutputStream.write(bytes); 
      } 
      fileInputStream.close(); 
      responseOutputStream.close(); 

     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

나는 그러나 파일이 손상, 엑셀 위의 코드로 파일을 다운로드 할 수 있어요. Microsoft Excel에서 열면 메시지가있는 팝업이 표시됩니다.

"파일 형식과 확장명이 일치하지 않습니다. 파일이 손상되거나 안전하지 않을 수 있습니다."

그리고 Excel 파일이 비어 있습니다.

코드를 실행 한 후에 원본 파일 (d : /test/test.xls)도 손상됩니다.

내가 뭘 잘못하고 있니?

+0

당신에게 엑셀 파일을 다운로드 attemting 전에 유효 확실 귀하의 의존성에 아파치 평민-IO-2.4를 추가하는 것을 잊었다? 프로세스 전에 이미 손상되었을 수 있습니까? – icza

+0

네, 그 점은 확실합니다. – MeesterPatat

+0

글쎄, 확실하게 한 가지는 확실히 게시 한 코드가 Excel 파일을 수정하거나 손상시키지 않는다는 것입니다. – icza

답변

1

Excel 파일 .xls의 공식 MIME 유형은 application/vnd.ms-excel이고 .xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet입니다.

또한 출력 스트림에 쓰기 전에 response.reset()을 수행하고 response을 닫기 전에 responseOutputStream.flush() (중요)을 수행하는 것이 좋습니다. 코드 아래

0

시도 :

File file = null; 
    InputStream in = null; 
    OutputStream outstream = null; 
    try { 
     response.reset(); 
     in = new FileInputStream(file); 
     response.setContentType("application/vnd.ms-excel"); 
     response.addHeader("content-disposition", "attachment; filename=data.xls"); 
     outstream = response.getOutputStream(); 
     IOUtils.copyLarge(in, outstream); 
    } 
    catch (Exception e) { 
     out.write("Unable to download file"); 
    }finally { 
     IOUtils.closeQuietly(outstream); 
     IOUtils.closeQuietly(in); 
     IOUtils.closeQuietly(out); 
     if (file != null) 
      file.delete(); 
    } 

망가

관련 문제