How to Download File using Axios Vue JS?

Posted by LaravelIndia - 1 month ago

You can see bellow peace of code for axios request example:

<!DOCTYPE html>
<html>
<head>
    <title>How to Download File using Axios Vue JS? - pakainfo.com</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>