상세 컨텐츠

본문 제목

UrlResource class를 사용한 파일 다운로드

WEB/스프링

by 비행학교브론즈 2023. 2. 14. 20:16

본문

 

@GetMapping("/download-ex")
    public ResponseEntity<Resource> downloadFile() throws MalformedURLException {
    
    /*
    프로젝트 위치에서 찾기
    UrlResource resource = new UrlResource("classpath:com/project/abcd.txt);
    
    ResourceLoader, url protocol 관련된 공식 문서 
    https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#resources-resourceloader
    */
    
    //절대 파일 경로로 찾기, 로딩될 파일이 로컬에 위치해 있음
        UrlResource resource = new UrlResource("file:" +  "/불러올/파일의/절대경로");

        //status 200으로 설정
        return ResponseEntity.ok()
        //header 설정
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=클라이언트에서표시될이름.확장자")
            //resource를 바디에 씀
            .body(resource);
    }

 

서버는    

/download-ex 로 요청받았을때

"불러올" 이라는 directory 밑의 "파일의" 라는 directory의  "절대경로"라는 file을 resource로 지정해서

HttpsStatus 200, filedown header를 만들고 body에 지정한 리소스를 써서 응답을 보냄.

 

 

ResourceLoader, url protocol 관련된 공식 문서

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#resources-resourceloader

관련글 더보기