React

[React, Spring Boot] 파일 다운로드(Blob)

mxxn 2023. 9. 7. 15:01

파일 다운로드

 : DB에 있는 원본 BLOB 데이터를 가져와 화면에서 다운로드

 

React

const downloadFile = async (event, doc) => {
    event.preventDefault();
    const downloadUrl = '다운로드 url'
    const result = await axios.get(downloadUrl, {responseType : 'blob'}) // responseType 중요

    let blob = new Blob([result.data], { type: result.headers['content-type'] })


    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.target = '_self'
    link.setAttribute("download", `파일명.확장자`);
    link.click()
}

SpringBoot

// Controller
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity

...
...

@GetMapping(value = "/다운로드 url")
    public ResponseEntity<ByteArrayResource> downloadFile(DTO dto) {

        byte[] fileData = downloadService.selectFile(dto); // Retrieve the file data from the database

        if (fileData != null) {
          ByteArrayResource resource = new ByteArrayResource(fileData);

          return ResponseEntity.ok()
              .contentType(MediaType.APPLICATION_OCTET_STREAM)
              .contentLength(fileData.length)
              .body(resource);
        } else {
          return ResponseEntity.notFound().build();
        }
     }

// service는 byte[]에 맞게 db에서 select 해온 blob 데이터를 return 해주면 된다.