JavaScriptLaravelVue js

Vue js download file via laravel API

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.

Related Articles

4 Comments

  1. Hi, thanks for sharing your amazing article! It could be more great if you’ve given detailed explanation on the following part,

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

    Like instead of giving just test pdf example, you can give all the other options like setOptions, rendering view, facades and so on.,

    However still it gives an outline, thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button

Adblock Detected

Please consider supporting us by disabling your ad blocker