In this article, I will share with you how to download files in VueJs using Axios with a simple example. as you know files uploading and downloading this a common feature in any web application. so, here i will share file downloading in vuejs with a simple example. just follow the steps.
As we know Axios js is very popular for HTTP requests. you can fire get, post, put, etc request using Axios js in Vue js, node js, react js, etc. but if you need the same requirement to download file response from API and used to give download using Axios js then how you can do that? i will help you to do file downloading using Axios.
axios({
url: 'http://localhost:8000/api/get-file',
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();
});
<!DOCTYPE html>
<html>
<head>
<title>Download File using Axios Vue JS? - HackTheStuff</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>
i hope you like this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to add new elements to DOM in jQuery
Use the jQuery append() or prepend() met...How to Compare current password with hash password in Laravel
In this article we will share with you h...Create REST API using Django Rest Framework
There are multiple ways to indite an API...Increase Session Timeout Limit in Laravel
Today, I will show you how to increase s...Laravel 8 Cron Job Task Scheduling Tutorial
Today I expounded simply step by step la...