Vue JS Download File using Axios

Download file using axios in vue js; Through this tutorial, i am going to show you how to download pdf file or zip file using vue js axios.

How to Download File using Axios Vue JS

  • Step 1 – Create New VUE JS App
  • Step 2 – Navigate to Vue Js App
  • Step 3 – Create Component
  • Step 4 – Add Component on App.vue

Step 1 – Create New VUE JS App

Run the following command on terminal to create new vue js app:

vue create my-app

Step 2 – Navigate to Vue Js App

Run the following command on command prompt to enter your vue js app root directory:

cd my-app

Step 3 – Create Component

Go to /src/components directory and create a new component called file-download.vue and add the following code into it:

<!DOCTYPE html>
<html>
<head>
    <title>How to Download File using Axios Vue JS? - Laratutorials.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 File</button>
  
</div>
  
<script type="text/javascript">
   
    var app = new Vue({
      el: '#app',
      methods: {
          onClick() {
              axios({
                    url: 'http://localhost:8000/test.pdf',
                    method: 'GET',
                    responseType: 'blob',
                }).then((response) => {
                     var fileURL = window.URL.createObjectURL(new Blob([response.data]));
                     var fURL = document.createElement('a');
   
                     fURL.href = fileURL;
                     fURL.setAttribute('download', 'file.pdf');
                     document.body.appendChild(fURL);
   
                     fURL.click();
                });
          }
      }
    })
  
</script>
  
</body>
</html>

Step 4 – Add Component on App.vue

Go to /src/ directory and App.vue file. And then add the following code into it:

<template>
    <FileDownload></FileDownload>
</template>
<script>
import FileDownload from './components/FileDownload';
export default {
  components: {
    FileDownload
  }
}
</script>

Conclusion

Download file using axios in vue js. In this tutorial, you have learned how to download pdf file or zip file using vue js axios.

Recommended VUE JS Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.