SPA Single Page Application ๋กœ ์ž‘์„ฑ์ค‘์ธ ์›น ์‘์šฉํ”„๋กœ๊ทธ๋žจ์—์„œ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ๋ฅผ ๊ตฌํ˜„ํ•  ๋•Œ, ์ƒˆ ์ฐฝ์œผ๋กœ ๋‹ค์šด๋กœ๋“œํ•  ํŒŒ์ผ์˜ URI๋ฅผ ์ œ๊ณตํ•ด์„œ ์ฒ˜๋ฆฌํ•˜๋ฉด ๋งค์šฐ ํŽธ๋ฆฌํ•˜๊ฒŒ ํŒŒ์ผ์„ ๋‹ค์šด๋กœ๋“œํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

const fileDownloadUri = 'ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ URI';
window.open(fileDownloadUri, '_blank');

ํŒŒ์ผ URI์™€ ํ•จ๊ป˜ ์ธ์ฆ์ด ํ•„์š”ํ•  ๋•Œ, ์ฟ ํ‚ค๋ฅผ ์‚ฌ์šฉ์ค‘์ด๋ฉด ๋™์ผํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

๊ทธ๋Ÿฐ๋ฐ, ์ฟ ํ‚ค๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , JWT ๋“ฑ์„ ์‚ฌ์šฉํ•ด์„œ ์š”์ฒญ ํ—ค๋”์— ๋ฐ์ดํ„ฐ๋ฅผ ์ œ๊ณตํ•˜๋Š” ํ˜•์‹์œผ๋กœ ์ธ์ฆ์„ ์ฒ˜๋ฆฌ์ค‘์ด๋ฉด, ์ƒˆ์ฐฝ์„ ์—ด์–ด์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ๋Š” ์ฒ˜๋ฆฌ๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

์ด ๋•Œ, ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๊ฐ„๋‹จํ•œ ์ฝ”๋“œ์กฐ๊ฐ์„ npm ํŒจํ‚ค์ง€๋กœ ๊ณต์œ ํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ“ข @bbon/filedownload ํŒจํ‚ค์ง€

npm: @bbon/filedownload ํŒจํ‚ค์ง€ ํŽ˜์ด์ง€์—์„œ ํŒจํ‚ค์ง€๋ฅผ ํ™•์ธํ•˜์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๐Ÿ›  ์„ค์น˜

$ npm install @bbon/filedownload
$ yarn add @bbon/filedownload

๐ŸŽฎ ์‚ฌ์šฉ

HTTP ์š”์ฒญ์€ ์‚ฌ์šฉ์ค‘์ธ ํŒจํ‚ค์ง€ ๋˜๋Š” API๋ฅผ ์‚ฌ์šฉํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์‘๋‹ต ํ˜•์‹์€ BLOB ์œผ๋กœ ์ง€์ •๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

AWS S3, Azure Storage, Google Cloud Storage ๋“ฑ์˜ ํด๋ผ์šฐ๋“œ ๊ฐ์ฒด ์ €์žฅ์†Œ์— ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ๋ฌผ๋ก , ์ง์ ‘ ๊ตฌํ˜„ํ•œ ์›น ์‘์šฉํ”„๋กœ๊ทธ๋žจ์˜ BLOB ์‘๋‹ต์—๋„ ์‚ฌ์šฉ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์ œ ์ฝ”๋“œ์—์„œ HTTP ์š”์ฒญ์€ Axios ํŒจํ‚ค์ง€๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

const requestConfig: AxiosRequestConfig = {
    ...Axios.defaults,
    responseType: 'blob',
};

Axios.get(fileDownloadUrl, requestConfig)
    .then((res) => {
        if (res) {
            const contentType =
                res.headers['content-type'] || 'application/octet-stream';
            const helper = new FileDownloadHelper();
            helper.download({
                data: res.data,
                filename: fileName,
                contentType,
            });
        }
    })
    .catch((err) => {
        console.error(err);
    })
    .finally(() => {
        setLoading(false);
    });

์ „์ฒด์ฝ”๋“œ๋Š” GitHub: bbon-filedownload-sample ์ €์žฅ์†Œ์—์„œ ํ™•์ธํ•˜์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๐Ÿ˜Ž ์˜ˆ์ œ ํŽ˜์ด์ง€์—์„œ ๋™์ž‘์„ ํ™•์ธํ•˜์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (๋‹ค์šด๋กœ๋“œ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด, ๋นจ๊ฐ„ ์ด๋ฏธ์ง€๋ฅผ ๋‹ค์šด๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค. ํ™•์ธํ•˜์‹ค ๋•Œ ๋ˆˆ๐Ÿ‘์„ ์กฐ์‹ฌํ•˜์‹ญ์‹œ์˜ค.)