본문 바로가기

웹 개발/Spring Boot

SpringBoot) 파일 다운로드 API 만들기

Controller

@GetMapping(value = "<api_url>")
public ResponseEntity<Resource> fileDownloadApi() throws IOException{
    return exampleService.fileDownload();
}

 

Service

...
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
...


public ResponseEntity<Resource> fileDownload() throws IOException{
    Path filePath = Paths.get("<file_path_string>");
    InputStreamResource resource = new InputStreamResource(new FileInputStream(filePath.toString()));
    String fileName = "<file_name_string>";
    logger.info("Success download input excel file : " + filePath);
    return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .cacheControl(CacheControl.noCache())
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
            .body(resource);
}

 

HTML

<a href="<api_url>">다운로드</a>

 

이렇게하면 다운로드 버튼을 누르면 해당 파일이 바로 다운로드 되는 API 완성!