Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download PDF from http response with Axios

Tags:

I am working on a Vue application with a Laravel back-end API. After clicking on a link I would like to do a call to the server to download a certain file (most of the time a PDF file). When I do a get request with axios I get a PDF in return, in the body of the response. I would like to download that file directly.

To give you a better view of how the response is looking like:

enter image description here (note: I know a real text response is better than an image but I don't see any way to return that because of the length of the actual PDF content..)

Is there any way of downloading that file with JavaScript or something? It has to be specific a direct download without clicking on the button again.

Code

// This method gets called when clicking on a link downloadFile(id) {     const specificationId = this.$route.params.specificationId;      axios         .get(`${this.$API_URL}/api/v1/suppliersmanagement/product-specifications/${specificationId}/fileupload/${id}/download`, {             headers: this.headers,         })         .then(response => {             console.log(response);             // Direct download the file here..         })         .catch(error => console.log(error)); }, 
like image 491
Giesburts Avatar asked Jul 25 '18 08:07

Giesburts


People also ask

How do I make a PDF downloadable from a website in HTML?

With the use of the <a> tag download attribute, we can download pdf files, images, word files, etc. The download attribute specifies that the target (the file specified in the href attribute) will be downloaded when a user clicks on the hyperlink.

How do I download files and images from the Internet using Axios in Javascript?

The solution to the previously mentioned problem, How To Download Files Using Axios, can also be found in a different method, which will be discussed further down with some code examples. axios({ url: 'http://api.dev/file-download', //your url method: 'GET', responseType: 'blob', // important }).


1 Answers

As @Sandip Nirmal suggested I've used downloadjs and that worked out pretty good! Had to make a few adjustments to my code but in the end it worked out.

My new code

// npm i downloadjs import download from 'downloadjs'  // method downloadFile(file) {     const specificationId = this.$route.params.specificationId;      axios         .get(`${this.$API_URL}/api/v1/suppliersmanagement/product-specifications/${specificationId}/fileupload/${file.id}/download`, {             headers: this.headers,             responseType: 'blob', // had to add this one here         })         .then(response => {            const content = response.headers['content-type'];            download(response.data, file.file_name, content)         })         .catch(error => console.log(error)); }, 
like image 172
Giesburts Avatar answered Oct 24 '22 17:10

Giesburts