How to Download File in VueJs using Axios?

In this article, I will share with you how to download files in VueJs using Axios with a simple example. as you know files uploading and downloading this a common feature in any web application. so, here i will share file downloading in vuejs with a simple example. just follow the steps. 

As we know Axios js is very popular for HTTP requests. you can fire get, post, put, etc request using Axios js in Vue js, node js, react js, etc. but if you need the same requirement to download file response from API and used to give download using Axios js then how you can do that? i will help you to do file downloading using Axios.

Axios HTTP code :

axios({
    url: 'http://localhost:8000/api/get-file',
    method: 'GET',
    responseType: 'blob',
}).then((response) => {
     var fileURL = window.URL.createObjectURL(new Blob([response.data]));
     var fileLink = document.createElement('a');
    
     fileLink.href = fileURL;
     fileLink.setAttribute('download', 'file.pdf');
     document.body.appendChild(fileLink);
     
     fileLink.click();
});

HTML Code :

<!DOCTYPE html>
<html>
<head>
    <title>Download File using Axios Vue JS? - HackTheStuff</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js" integrity="sha256-S1J4GVHHDMiirir9qsXWc8ZWw74PHHafpsHp5PXtjTs=" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">
  <button @click="onClick()">DownLoad</button>
</div>
<script type="text/javascript">
   
    var app = new Vue({
      el: '#app',
      methods: {
          onClick() {
            axios({
                  url: 'http://localhost:8000/my.pdf',
                  method: 'GET',
                  responseType: 'blob',
              }).then((response) => {
                   var fileURL = window.URL.createObjectURL(new Blob([response.data]));
                   var fileLink = document.createElement('a');

                   fileLink.href = fileURL;
                   fileLink.setAttribute('download', 'file.pdf');
                   document.body.appendChild(fileLink);

                   fileLink.click();
              });
          }
      }
    })
</script>
</body>
</html>

i hope you like this article.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

1 Comment

SA
Dhiren
September 11, 2021

I have done like above code but downloaded file is corrupted and can't open I have tried many other codes also but still fail to save response file from api correctly in readable xlsx format