Vue js download file via laravel API

download file via axios

Hello buddy, I hope you are doing well, in this article we will learn about how to download a pdf file via Vue js Axios and laravel as backed API.

I understood that you search over enormous articles for this stuff but don’t get the working solution but we have one. The user doesn’t go bared hand from our website.

We will follow the below steps to download the file via laravel API

  1. Write the code in controller
  2. Write the code in vue template
  3. Test Integration

Step:1 Write the code in controller

In the below code I have directly targeted the pdf file, hope you have stored the pdf file in your laravel project directory.

my controller is inside app/http/Controllers/PdfController .php write the below code in your controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;


class PdfController extends Controller
{

    public function index()
    {
        return view('pdf.index');
    }

    public function create()
    {
        $pdf = public_path('pdf/test.pdf');
        return response()->download($pdf);
    }
}

Step:2 Write the code in vue template

Now write the below code in your vue template, to download the pdf file on click

<template>
    <div id="app">
  <button @click="onClick()">DownLoad</button>
</div>
</template>
<script>
    import axios from 'axios'
    export default {
        methods: {
             onClick() {
            axios({
                  url: 'api/downloadPdf',
                  method: 'GET',
                  responseType: 'arraybuffer',
              }).then((response) => {
                   let blob = new Blob([response.data], {
                            type: 'application/pdf'
                        })
                        let link = document.createElement('a')
                        link.href = window.URL.createObjectURL(blob)
                        link.download = 'test.pdf'
                        link.click()
              });
          }
        }

    }

</script>

Step:3 Test the integration

Now when you click on the button it will trigger vuejs on the click method, and download the pdf file.

I hope now you understood how we can download files via Axios in Vue js and laravel as the backend, it helps you please rate me 5.

5 1 vote
Article Rating

Please click on advertisment 🙏,helps to maintain website cost
Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x