Reputation: 9354
I want to download the zip file from the server using PHP Laravel. The Laravel passes zip files through following return command:
return response()->download($file);
It downloads the zip file when I hit the route URL for the controller in the browser, and it also downloads the zip file when I use window.open(url)
in the Angular but it is not secure as anyone can download the file. The user has to authenticate before downloading the file but I cannot pass header with window.open(url)
, therefor I need a different approach to achieve this.
I went through most of the questions here, and they suggest to use FileSaver and Blob. I tried to test with those but didn't work and it's because the API doesn't pass the zip file to the client.
Here is the Angular http.get:
return http.get('localhost:8000/dashboard/backup')
.subscribe(res => {
console.log('Successfull');
}, err => {
console.log(err);
});
I can get the file path, but the path is not public and cannot download it using Angular. The path is returned as Application/XAMP.... and when I set it as HREF and click on it, it loads in browser as localhost:4200/Application/XAMP....
In the console log, I have an invalid character at JSON file line 1. Why is the zip file passed as JSON?
Upvotes: 1
Views: 3763
Reputation: 941
use post method and responseType arraybuffer
$http.post('localhost:8000/dashboard/backup', {}, {responseType:'arraybuffer'}){
}
Upvotes: 2
Reputation: 2353
This is correct what ever you are doing. This is the only way how we can download zip with angular and laravel. But security purpose how you can manage is put your route inside projected middleware. So that unauthorized person won't be download.
Upvotes: 0
Reputation: 9354
@Sameera suggestion works. I added responseType
and changed get
to post
.
Here is full solution:
return http.post('localhost:8000/dashboard/backup', {}, {responseType:'arraybuffer'})()
.subscribe(res => {
const blob = new Blob([res], {type: 'application/octet-stream'});
FileSaver.saveAs(blob, 'backup.zip');
}, err => {
console.log(err);
});
FileSaver is used to save file.
Upvotes: 0