반응형

뭐 pdf.js 같은 view를 쓰는 방법도 있지만

이 방법이 생각보다 깔끔하다..

 

스크립트 단에서 window.open 으로 호출하고

서버단에서 아래 코드를 작성하면 된다.

 

밑에 소스는 노트패드++같은데 붙여넣어서 보면 편하다~

 

FileInputStream fis = null;

BufferedOutputStream bos = null;

 

try {

String pdfFileName = "C:/upload/TEST.pdf";

File pdfFile = new File(pdfFileName);

 

//클라이언트 브라우져에서 바로 보는 방법(헤더 변경)

response.setContentType("application/pdf");

 

//★ 이 구문이 있으면 [다운로드], 이 구문이 없다면 바로 target 지정된 곳에 view 해줍니다.

response.addHeader("Content-Disposition", "attachment; filename="+pdfFile.getName()+".pdf");

 

 

//파일 읽고 쓰는 건 일반적인 Write방식이랑 동일합니다. 다만 reponse 출력 스트림 객체에 write.

fis = new FileInputStream(pdfFile);

int size = fis.available(); //지정 파일에서 읽을 수 있는 바이트 수를 반환

byte[] buf = new byte[size]; //버퍼설정

int readCount = fis.read(buf);

 

response.flushBuffer();

bos = new BufferedOutputStream(response.getOutputStream());

bos.write(buf, 0, readCount);

bos.flush();

 

 

catch(Exception e) {

e.printStackTrace();

} finally {

try {

if (fis != null) fis.close(); //close는 꼭! 반드시!

if (bos != null) bos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

 

 

[출처] [Java] Pdf 파일 다운로드 or 바로보여주기|

http://blog.naver.com/PostView.nhn?blogId=onandme&logNo=220529022550&parentCategoryNo=&categoryNo=&viewDate=&isShowPopularPosts=false&from=postView

작성자 onandme

반응형

+ Recent posts