파일 다운로드
: 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 해주면 된다.
'React' 카테고리의 다른 글
[React, Spring Boot] Whitelabel Error Page문제 (0) | 2023.09.07 |
---|---|
[React, TypeScript] TradingView lightweight-charts 사용 (0) | 2023.09.07 |
[React] JS Bites: React hook is called in a function which is neither a React function or a custom React Hook (0) | 2023.09.07 |
[React] cannot read properties of undefined (reading '컬럼명') 오류 (0) | 2023.09.07 |
[React] Table 사용 시 주의 (0) | 2023.09.05 |