2

I am using angular and laravel. on a post request PHP creates a file and responds with the filename. How to use that filename and trigger download from angular.

api request

    var promise = $http.post('api/admin/ecs/singleecs', data).
        success(function (response) {
             //trigger file download
    })

php

PDF::loadHTML($html)->setPaper('a4')->setWarnings(false)->save('public/temp/'.$filename.'.pdf');
return $filename;

2 Answers2

0

To solve this issue I would take the following steps:

  1. Create a hidden a element on the page.

    <a id="fileDownloadLink" ng-hide="true" ng-href={downloadUrl} />
    
  2. Use the following code to set the download URL and trigger the download.

    $scope.downloadUrl = response.data.fileName;
    
    var fileDownloadLink = document.getElementById("fileDownloadLink");
    fileDownloadLink.target = "_blank"; // Opens the file in a new window.
    fileDownloadLink.click();       
    
ACOMIT001
  • 510
  • 1
  • 7
  • 21
0

You can use $window.location to trigger the download. This will work only if "Content-Disposition: attachment" is in the response header of the resource_url:

var promise = $http.post('api/admin/ecs/singleecs', data)
                   .then(function (response) {
                     $window.location = response.resource_url;
                   });

Note: This is the angular version of the jQuery pattern illustrated here: https://stackoverflow.com/a/11620720/271178

Community
  • 1
  • 1
Luiz C.
  • 746
  • 11
  • 22