기록하는 코더

[Spring] 파일 다운로드 본문

JAVA/spring

[Spring] 파일 다운로드

damda_di 2023. 2. 2. 15:28
	// SpringFramework를 이용한 파일 다운로드
	/* MINE(Multipurpose Internet Mail Extensions)
	 문자열을 전송할 때는 7비트 아스키파일로 전송하여 사용하지만
	 사진, 음악, 동영상, 문서 파일을 보낼 땐 8비트 데이터(바이너리 데이터)를 사용함
	 이것을 전송하기 위해서는 바이너리 데이터를 텍스트로 변환하는 인코딩 작업이 필요함
	 
	 MIME은 이런 인코딩 방식의 일종	. 인코딩 + data type(contents type)
	 image/jpeg
	*/
	// 요청URI : /board/goHome1102
	@GetMapping("/board/goHome1102")
	public ResponseEntity<byte[]> home1102() throws IOException{
		log.info("home1102에 왔다.");
		// 입력스트림 (00110111011000..)
		InputStream in = null;
		ResponseEntity<byte[]> entity = null;
		
		HttpHeaders headers = new HttpHeaders();
		String fileName = "C:/eclipse_202006/workspace/springProj/src/main/webapp/resources/upload/2023/01/31/059b8af4-f415-4a63-82fc-13fe33bde881_animal (13).jpg";
		try {
			in = new FileInputStream(fileName);
			// APPLICATION_OCTET(8비트)_STREAM(순수한 바이너리 데이터) : 
			// 표준으로 정의되어 있지 않은 파일인 경우 지정하는 타입
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.add("Content-Disposition", "attachment;filename=\"" + 
				   new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\""); // 파일에 한글이 들어갈 수 있으므로 getByte("UTF-8")로 한글처리
			// Content-Disposition : 웹브라우저에서 다운로드 창을 띄움
			// 		이 뒤에는 파일 이름과 확장자를 지정해야 함 (Content의 속성을 지정해줌)
			// 		스트림 파일을 통해 writer해줌
			
			//		ResponseEntity<String> entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
			entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in),
					headers, HttpStatus.CREATED);
			
		} catch (FileNotFoundException e) {
			log.info(e.getMessage());
			entity = new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
		}finally {
			in.close();
		}
		return entity;
	}

 

 

 

 

@Slf4j
@Controller
public class DownloadController {
	
	// 요청URI : http://localhost/download?fileName=/2023/01/30/922035f6-e453-434e-9d69-dd68588308f7_nullPointer.jpg
	// 요청파라미터 : fileName=/2023/01/30/922035f6-e453-434e-9d69-dd68588308f7_nullPointer.jpg
	@ResponseBody
	@GetMapping("/download")
	public ResponseEntity<Resource> download(@RequestParam String fileName) {
		log.info("fileName : " + fileName);
		// parameter는 RequestParam
		// VO는 ModelAndView
		
		// resource : 다운로드 받을 파일(자원)
		Resource resource = new FileSystemResource(
				 "C:/eclipse_202006/workspace/springProj/src/main/webapp/resources/upload/"
				+ fileName
				);
		// 922035f6-e453-434e-9d69-dd68588308f7_nullPointer.jpg
		String resourceName = resource.getFilename();
		// header : 인코딩 정보, 파일명 정보
		HttpHeaders headers = new HttpHeaders();
		// Content-Disposition : 다운로드창 열기
		try {
			headers.add("Content-Disposition", "attchment; filename=" + new String(resourceName.getBytes("UTF-8"), "ISO-8859-1"));
		} catch (UnsupportedEncodingException e) {
			log.info(e.getMessage());
		}
		
		return new ResponseEntity<Resource>(resource,headers, HttpStatus.OK);
		
	}
}

'JAVA > spring' 카테고리의 다른 글

[Spring] 페이징 처리  (0) 2023.02.09
[Spring] form 태그 라이브러리  (0) 2023.02.06
[Spring] ajax 데이터 처리  (0) 2023.02.02
[Spring] Mybatis - resultMap  (0) 2023.01.31
[Spring] 파일업로드 MultipartFile  (0) 2023.01.27