[Axios] Consume Stream for download
Opened this issue · 0 comments
DolphaGo commented
여기서 말하는 것은 안된다고 하고 있다. 근데 이건 2016년 글임.
다음과 같이 커스텀을 하여, axios로도 browser 상에서 stream data를 받아 다운로드를 만들 수 있음
- 예를 들어 엑셀 다운로드를 한다고 할 때, 클릭 시에 데이터를 stream 형태로 서버로부터 받아와서 파일로 저장하는 상황을 예시로 들 수 있을 것이다.
그러므로, axios를 사용한다면 다음과 같이 커스텀을 해보자.
export const downloadOnBrowser = (data: BlobPart, headers: AxiosResponseHeaders, fileName: string) => {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement('a');
const contentDisposition = headers['content-disposition']; // 파일 이름
if (contentDisposition) {
const [fileNameMatch] = contentDisposition.split(';').filter(str => str.includes('filename'));
if (fileNameMatch)
[, fileName] = fileNameMatch.split('=');
}
link.href = url;
link.setAttribute('download', fileName);
link.style.cssText = 'display:none';
document.body.appendChild(link);
link.click();
link.remove();
}
그리고 request config에 responseType: blob
이라고 추가해주면 된다.
그렇게 되면, response data로 blobPart 를 얻게 된다. 이게 곧 스트림이라고 이해하면 된다.
export function XXX(body: YYY) {
return request.post('/api/v1/abc/def', body, {
responseType: 'blob'
}).then(res => {
downloadOnBrowser(res.data, res.headers, 'dolphago.csv')
})
}