[React] 파일 다운로더

Tags
Column

1. 소스코드(lib/api/common/s3.js)

import Downloader from '@/components/common/uploader/downloader'; export default class S3Downloader { constructor({bucket, key}) { this.downloadLink = `/api/upload/file?bucket=${bucket}&key=${key}`; this.downloader = new Downloader({ config: {}, onDownload: (response) => this.onDownload(response), onError: (error) => this.onError(error) }); this.enableFileDownload = this.enableFileDownload.bind(this); } enableFileDownload() { this.downloader.getDownloadLink(this.downloadLink); } onDownload(response) { const url = response.body.url; var link = document.createElement("a"); link.download = "temp"; link.href = url; document.body.appendChild(link); link.click(); document.body.removeChild(link); } onError(response) { alert("다운로드 에러 발생!"); console.log(response); } }
 
 

2. 사용방법

import S3Downloader from "@/lib/api/common/s3"; // 클래스 임포트 // ex) response = {bucket: "...", key: "..."} const s3 = new S3Downloader({bucket: response.bucket, key: response.key}); // 다운로드할 파일의 버켓 값과 키 값을 클래스 초기화 시 전달 s3.enableFileDownload(); // 실행 과정 // 1. 버켓과 키를 가지고 api 서버에 임시 다운로드 링크 발급 요청 // 2. api 서버로부터 전달받은 링크를 임시 다운로드 링크를 만든 후 자동 다운로드 수행