Vue.js

Vue File Download

소밍소밍 2021. 7. 9. 09:50

Vue에서 파일 다운로드할 때 사용하는 두가지 방법. 두가지 모두 responseType: "blob"을 명시하는 것이 중요하다.

 

 

라이브러리 설치하는 버전

https://www.npmjs.com/package/js-file-download 라이브러리 설치 후 아래 코드로 작성하면 된다.

 

const FileDownload = require('js-file-download');
  
axios.get('/uri/uri/' + variable, {
   responseType: "blob"
}).then(response => {
   FileDownload(response.data, attachFileName);
}).catch(exception => {
   alert("파일 다운로드 실패");
});

 

라이브러리 설치하지 않는 버전

axios.get('/uri/uri/' + variable, {
   responseType: "blob"
}).then(response => {
   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', attachFileName); //or any other extension
   document.body.appendChild(link);
   link.click();
}).catch(exception => {
   alert("파일 다운로드 실패");
});