Download PDF from http response with Axios Download PDF from http response with Axios vue.js vue.js

Download PDF from http response with Axios


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 downloadjsimport download from 'downloadjs'// methoddownloadFile(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));},


You have 2 options for this. If you want to do it from server and if you are using Node.js as a backend. You can do it easily using res.download method of express. You can follow this answer for that Download a file from NodeJS Server using Express.

But if you want to handle it from client then there are few options since you can't use axios, XHR, fetch to download file directly. You can either use download.js or write your own code in following way.

return axios({    url: '/download', // download url    method: 'get',    headers: {      Accept: 'application/json',      'Content-Type': 'application/json',      mode: 'no-cors'    }  })    .then(response => response.blob())    .then(blob => {      var url = window.URL.createObjectURL(blob)      var a = document.createElement('a')      a.href = url      a.download = fileName      a.click()      a.remove()      setTimeout(() => window.URL.revokeObjectURL(url), 100)    })

Since response returned from server is in json format you need to convert it into ObjectURL and set it to anchor tag.

If you sneak inside download.js code you will find same implementation.


You can do it like this

download(filename) {  fetch(url , { headers })  .then(response => response.blob())  .then(blob => URL.createObjectURL(blob))  .then(uril => {    var link = document.createElement("a");    link.href = uril;    link.download = filename + ".csv";    document.body.appendChild(link);    link.click();    document.body.removeChild(link);  });}

here I want to download a CSV file, So I add .csv to the filename.