Download using the Xios?

Asked

Viewed 6,638 times

1

I am using Axios to perform my application requests, and in one of the GET requests it returns a PDF file. When I do the GET request by Postman it opens a window to choose where to save the file, but when I do the request by my application it does not download. Which method should I use to download the file??

axios.get('/server/pdfs')
.then(function (response) {
  //Qual método usar aqui para efetuar o download??
})
.catch(function (error) {
  console.log(error)
})

I’ve already looked at the official documentation on Github and it doesn’t explain how to download using Axios.

1 answer

3


Just create the file with the Blog and passing the mime type. Then open a new link passing the URL encodada. You can also use the link created in items of the type a and iframe.

axios.get('/server/pdfs')
.then(function(response) {
    var blob = new Blob([response.data], {
          type: 'application/pdf'
    });
    var url = window.URL.createObjectURL(blob)
    window.open(url);
  })
  .catch(function(error) {
        console.log(error)
});
  • After having configured the URL he opened the PDF when the request was made, but opened another PDF, not the same that is returning when I request with Postman, I will put here my server code: app.get('/baixarpdf', function (req, res) { 
 let file = fs.createReadStream('C:/TestePDF/pdfs/teste2.pdf');
 let stat = fs.statSync('C:/TestePDF/pdfs/teste2.pdf');
 res.setHeader('Content-Length', stat.size);
 res.setHeader('Content-Type', 'application/pdf');
 res.setHeader('Content-Disposition', 'attachment; filename=teste2.pdf');
 file.pipe(res);
})

  • It was a bit unnatural, with each res declared and each Let is a line break. I really appreciate your help Bruno

  • @Leonardoebert, this code you posted in the comment is Node.js correct? Continue opening the same file?

  • The code above is Node, when I do the request by Postman opens the correct file that is in a folder and that I specified the path, when I do the request by my client it opens a PDF that he creates on time, with a random name like: e792586d-ffc2-49eb-8d0b-66e75b7effda, and that "name" always changes

  • I even took a look and compared the requests of Postman and my client and saw that in Postman is configured "contenttype: 'application/pdf', while in my client is configured 'application/json, text/Plain, /'. I am using Axios and I am not able to configure my client’s header to 'application/pdf'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.