Download excel file with Vue.js 2 and Laravel 5.4
I was try to create a download button in my Vue.js test file with this module:
<template>
<div class="container">
<h1>profile</h1>
<button @click="download" class="btn btn-success">download</button>
<h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci hic labore nesciunt perspiciatis quibusdam voluptatum! A alias dolores, eligendi fugit molestiae quam quo ratione recusandae ut vel, vitae voluptates! Deserunt!</h4>
<!--<ul v-if="posts && posts.length">-->
<!--<li v-for="post of posts">-->
<!--<p><strong v-text="post.title"></strong></p>-->
<!--<p v-text="post.body"></p>-->
<!--</li>-->
<!--</ul>-->
</div>
</template>
<script>
export default{
data(){
return {
posts: [],
errors: []
};
},
// Fetches posts when the component is created.
created() {
},
methods: {
/**
* Prepare the component.
*/
download() {
var PUBLIC_SERVER_AUTH_TOKEN = "Bearer YYY";
var LOCAL_SERVER_AUTH_TOKEN = "Bearer XXX";
var PUBLIC_SERVER_BASE_URL = 'https://api.xxx.com/api/v1/role?file=xls';
var LOCAL_SERVER_BASE_URL = 'http://xxx.xxx.xxx.xxx:82/api/v1/role?file=xls';
var instance = axios.create({
baseURL: PUBLIC_SERVER_BASE_URL
// baseURL: LOCAL_SERVER_BASE_URL
});
instance.defaults.headers.common['Authorization'] = PUBLIC_SERVER_AUTH_TOKEN;
instance.defaults.headers.common['Content-Type'] = 'text/html; charset=utf-8';
instance.get()
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.xls');
document.body.appendChild(link);
link.click();
}
).catch(function (error) {
if (error.response) {
console.log('error.response');
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log('error.request');
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
console.log('else');
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log('final of catch');
console.log(error.config);
});
}
}
};
</script>
when i use it locally ,file was downloaded but when use “PUBLIC_SERVER_BASE_URL” can’t get the file, however i can get excel file in “POSTMAN” and when i see in chrome debugger in network tab i can see response of file but it doesn’t download by browser.
from Laravel Questions and Answers https://laravelquestions.com/laravel/download-excel-file-with-vue-js-2-and-laravel-5-4/
via Lzo Media
No comments:
Post a Comment