내 세상

[Spring] ResponseEntity / File Download 구현 본문

Technical/Spring

[Spring] ResponseEntity / File Download 구현

sga8 2021. 7. 2. 13:25
728x90
반응형
	private HttpHeaders makeHttpHeaders(String filename) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filename + "\";");
		headers.set(HttpHeaders.TRANSFER_ENCODING, "binary");
		return headers;
	}
    
	private ResponseEntity<?> downloadFile(HttpServletRequest request, Map<String, Object> map, String originUrl)
			throws Exception {

		String prefix = constants.getPrefix();
		String subPath = getArray(partPathArr, 0, 2);


		File[] fileList = new File(prefix + subPath).listFiles();
		// 코드 중간 생략
		if (fileName.isEmpty()) {
			return ResponseEntity.notFound().build();
		}

		String path = prefix + subPath + File.separator + fileName;

		InputStreamResource resource = new InputStreamResource(new FileInputStream(path));
		return ResponseEntity.ok().headers(makeHttpHeaders(fileName)).contentLength(new File(fileName).length())
				.contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
	}

 

 

InputStreamResource가 다른 ByteArrayResource, Resource, FileSystemResource에 비해서 대용량을 사용할 수 있다고함.

추후 비교 예정.

728x90
반응형