본문 바로가기

낙서장/Spring

Spring PDF 파일 ResponseEntity로 보여주기

<Spring Package>

ResponseEntity<T> : HttpEntity 부모로 상속받은 클래스 이다. ResponseEntity 클래스는 헤더와 본문으로 구성된 HTTP 요청 또는 응답 엔티티를 나타낸다.

InputStreamResource : 특정 자원(resource) 구현이 적용 되지 않는 경우에만 사용한다. 특히 ByteArrayResource경우 파일 기반 Resource 구현을 선호한다. <-- 데이터베이스 BLOB(PDF) 데이터 저장용도 

 

코드해석 : 데이터베이스 테이블 컬럼에서 파일 이름과 조건에 맞는 자원을 Object로 가져온다. 가져온 자원에 byte 배열로 저장된 pdf 자원을 SerialBlob 객체를 생성 시 파라미터 자원으로 사용한다. SerialBlob 메소드 중에서 InputStream 리턴하는 메소드를 이용하여 InputStreamResource 객체를 생성할 때 파라미터 자원으로 사용한다. 리턴타입으로는 ResponseEntity를 이용 하는데 ResponseEntity 제네릭 타입을 InputStreamResource 지정한다. Controller 반환할 때 HTTP header , contentLength, contentType, body 설정한 객체를 반환시킨다.


<source>

public ResponseEntity<InputStreamResource> getPdfOutput(HttpServletRequest request, HttpServletResponse response, String fileName) throws Exception {
				PdfVO pvo = pMapper.selecetPdf(fileName);
				
				if(pvo == null) {
					throw new NoDataException("잘못된 URL입니다.");
				}
				
				SerialBlob serB = new SerialBlob(pvo.getFileData());
								
				HttpHeaders headers = new HttpHeaders();
				headers.add("content-disposition", "inline;filename="+ fileName);
										
				InputStreamResource resource = new InputStreamResource(serB.getBinaryStream());

				return ResponseEntity.ok()
							 .headers(headers)
							 .contentLength(serB.length())
							 .contentType(MediaType.parseMediaType("application/pdf"))
							 .body(resource);
                
                /* Spring Vresion 4.1 미만인 경우 
                HttpHeaders headers = new HttpHeaders();
                headers.add("content-disposition", "inline;filename="+ id);
                headers.setContentType(MediaType.parseMediaType("application/pdf"));
                headers.setContentLength(serB.length());

                InputStreamResource resource = new InputStreamResource(serB.getBinaryStream());

                return new ResponseEntity<InputStreamResource>(resource, headers, HttpStatus.OK);
                */
		
	}

'낙서장 > Spring' 카테고리의 다른 글

Spring Image DataBase Insert  (0) 2022.02.21
[url mapping pattern] /* /** 차이  (0) 2021.10.13
Oracle DataBase PDF파일 값 넣기!!  (0) 2021.09.07
Spring 다른 서버에 파일 보내기(FTP)  (0) 2021.09.07
Spring Project Setting  (0) 2021.08.19