본문 바로가기

Spring Boot

[Svelte + Springboot] Svelte에서 파일다운로드 구현

반응형

1. Svelte 구성 요소에 다운로드를 트리거하는 버튼을 만듭니다.

<button on:click={downloadFile}>Download File</button>

 

2. 파일에 대한 요청을 서버에 보내는 함수를 만듭니다.

async function downloadFile() {
  const response = await fetch("/api/download");
  const blob = await response.blob();

  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "file.txt";
  link.click();
}

 

3. Spring Boot 애플리케이션에서 REST을 생성하여 파일을 반환합니다.

import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class FileDownloadController {
  @GetMapping("/download")
  public ResponseEntity<Resource> downloadFile() {
    // Load the file from disk or retrieve it from a database
    Resource file = ...;

    return ResponseEntity.ok()
      .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"file.txt\"")
      .body(file);
  }
}

Svelte 구성 요소에서 "파일 다운로드" 버튼을 클릭하면 GET 요청이 Spring Boot 응용 프로그램의 /api/download로 전송됩니다. 엔드포인트는 응답을 파일 첨부로 처리해야 함을 나타내기 위해 Content-Disposition 헤더가 설정된 이진 스트림으로 파일을 반환합니다.

그런 다음 Svelte 함수는 파일에 대한 동적 링크를 만들고 다운로드를 트리거합니다. 파일은 이미지, PDF 문서 또는 텍스트 파일과 같은 모든 유형의 이진 데이터일 수 있습니다.

반응형