Implementing a file download feature in Vue.js with Laravel involves creating an API endpoint in Laravel to handle the file download, and then making a request to that endpoint from your Vue.js component. Here's a step-by-step guide:
Create a Controller:
Create a new controller or use an existing one to handle file download. Let's assume you have a DownloadController.php
:
phpphp artisan make:controller DownloadController
Define a Download Method:
In your DownloadController.php
, define a method to handle the file download:
php// app/Http/Controllers/DownloadController.php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
class DownloadController extends Controller
{
public function downloadFile($filename)
{
$file = storage_path('app/public/' . $filename); // Change the path as needed
return response()->download($file);
}
}
Create a Route:
Add a route in your routes/web.php
or routes/api.php
file:
php// routes/web.php or routes/api.php
use App\Http\Controllers\DownloadController;
Route::get('/download/{filename}', [DownloadController::class, 'downloadFile']);
Make a Request from Vue.js:
In your Vue component, make a request to the Laravel endpoint to initiate the file download. You can use the axios
library for this.
bashnpm install axios
Use Axios to Download File: In your Vue component, use Axios to make a GET request to the Laravel endpoint:
javascript// Your Vue component
<template>
<div>
<button @click="downloadFile">Download File</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
methods: {
downloadFile() {
const filename = 'your-file-name.ext'; // Provide the actual filename
axios({
method: 'get',
url: `/download/${filename}`,
responseType: 'blob', // Important for file downloads
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
});
},
},
};
</script>
Adjust the filename
variable in the Vue component with the actual filename you want to download.
This is a basic example, and you may need to adjust it based on your specific needs and the structure of your application.