PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, February 17, 2022

[FIXED] Download file from php server with vuejs

 February 17, 2022     cakephp, cakephp-3.0, vue.js     No comments   

Issue

My application is running on CakePHP with vuejs as front end js framework.

I am making an axios request to server for generating the output file and file is generated in webroot folder of cakephp.

Api()
.get('/articles/downloadFile')
.then(response => {
});

How can I download the generated file through vuejs?


Solution

You need to pass responseType as blob in the axios call. Something like this

.get('/articles/downloadFile', {responseType: 'blob'})

And then, in when the promise resolves to generate a href element in the DOM and download the item.

.then((response) => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'image.png');
    document.body.appendChild(link);
    link.click();
})

I'm assuming that you are downloading an image, you need to change the name and the extension for your use case.

Here's a fiddle with a complete example.

NB: for this to work (even just the GET call) your CORS policy must allow this call.



Answered By - Radu Diță
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing