Jsp

[jsp] 파일 다운로드: FileInputStream, ServletOutputStream

쟈근꿈틀이 2022. 5. 31. 10:48
728x90

FileInputStream 클래스

 

FileInputStream 생성자
  • FileInputStream(String filePath) throws FileNotFoundException: filePath로 지정한 파일에 대한 입력 스트림을 생성
  • FileInputStream(File fileObj) throws FileNotFoundException: fileObj로 지정한 파일에 대한 입력 스트림을 생성

 

FileInputStream 메서드
  • int close() throws IOException: InputStream을 닫음 
  • int read(byte buf[], int offset, int numBytes) throws IOException: InputStream에서 numBytes만큼을 읽어 *buf[]의 offset 위치에서부터 저장하고 읽은 바이트 수를 반환(더 이상 읽을 데이터가 없다면 -1을 반환)

* buf[]:파일의 데이터를 저장 

 

 

FileInputStream 클래스InputStream 클래스를 상속받은 후손 클래스하드 디스크에 존재하는 파일로부터

바이트 단위의 입력을 받는 클래스이다.

이 클래스는 스트림(출발 지점과 도착 지점을 연결하는 통로)을 생성하는 클래스이다.

 

생성자의 파라미터는 File 객체를 주거나 파일의 이름을 직접 String 형태로 줄 수 있다. 

일반적으로 파일의 이름을 String 형태로 주는 경우가 많은데 파일이 존재하지 않을 가능성도 있으므로 Exception 처리를 해야 한다.

 

[writeService.jsp]: 클라이언트의 게시글 등록 처리
-> 클라이언트가 업로드한 파일 웹 서버의 하드디스크에 저장되는 위치
(클라이언트별로 폴더를 만들어서 파일을 저장)
String saveFolder = "C:\\javas\\upload\\" + member.getId();
File file = new File(saveFolder);

[view.jsp]: 클라이언트가 요청한 특정 게시글 정보를 화면에 띄움
-> 게시글의 첨부 파일명을 클릭하면 웹 서버에 fileDown.jsp를 요청
(+작성자 아이디와 파일명을 전달)
첨부 파일 : <a href="fileDown.jsp?fileName=<%=fileName%>&writeId=<%=writeId%>"><%=fileName %></a></div>

String saveFolder = "C:\\javas\\upload\\" + writeId + "\\" + fileName;
File file = new File(saveFolder);

FileInputStream iStream = new FileInputStream(file);

클라이언트의 요청 url로 전달 받은 작성자 아이디와 파일명을 통해 클라이언트가 다운로드 받기 원했던 특정 파일에 대한 입력 스트림을 생성한다.  


 

Http Response Message의 구조

 

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

*Content-Disposition 헤더

  • 일반적인 HTTP 응답에서 Content-Disposition 헤더는 컨텐츠가 브라우저에 inline 되어야 하는 웹페이지 자체이거나 웹페이지의 일부인지, 아니면 attachment로써 다운로드 되거나 로컬에 저장될 용도록 쓰이는 것인지를 알려주는 헤더

웹 서버가 클라이언트에게 텍스트가 아닌 파일과 파일명을 전달하기 위해서 응답 헤더의Content-Type을 application/octet-stream으로 설정하고, attachment의 파일명을 fileName으로 설정 하여 클라이언트가 해당 파일을 다운로드 할 수 있게 하였다. 

 


ServletOutputStream 클래스

 

 

 

 

 

 

 

 

[참고]

 

[JAVA] ByteStream : FileInputStream / FileOutputStream

ByteStream : FileInputStream / FileOutputStream 직접 키보드를 통하여 입력하는 데이터는 대개 임시 자료인 경우가 많다. 중요한 자료는 대부분 데이터베이스에 저장되어 있거나 파일 시스템에 저장된다. F

xzio.tistory.com

 

 

ServletOutputStream (Java(TM) EE 7 Specification APIs)

Provides an output stream for sending binary data to the client. A ServletOutputStream object is normally retrieved via the ServletResponse.getOutputStream() method. This is an abstract class that the servlet container implements. Subclasses of this class

docs.oracle.com

 

728x90