본문 바로가기

Spring Boot

[React + Spring Boot ] Spring Boot 백엔드를 사용하여 React 앱에서 파일 다운로드를 구현하는 방법

반응형

React component

import React from 'react';

const FileDownloader = () => {
  const handleDownload = async () => {
    try {
      const response = await fetch('http://localhost:8080/download');
      const blob = await response.blob();
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'file.pdf';
      link.click();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <button onClick={handleDownload}>Download</button>
  );
};

export default FileDownloader;

 

Spring Boot controller

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class FileDownloadController {
  @GetMapping("/download")
  public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
    File file = new File("src/main/resources/static/file.pdf");
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
        .contentType(MediaType.APPLICATION_PDF)
        .body(resource);
  }
}

React 구성 요소에서 "Download" 버튼을 클릭하면 GET 요청이 Spring Boot 끝점으로 전송됩니다. 엔드포인트는 내용 유형 및 내용 처리를 포함하여 적절한 헤더가 설정된 응답 엔티티로 파일을 반환합니다. 그런 다음 React 구성 요소는 응답 본문에서 URL을 생성하고 새 탭에서 URL을 열면 브라우저가 파일을 다운로드하도록 트리거합니다. 

반응형