Cris69
Cris69

Reputation: 600

Download a file from Angular.js with Express.js

In my MEAN application I need to provide a link to download a file, the link must be hidden and not accessible by unauthorized users. So I came up with this idea of keeping the files inside the server directory and let Angular.js send with ng-click="download()" an $HTTP request to express.js with the file ID to download, and (possibly) the user id/pwd. First of all is this a safe solution? Second, here is my code that doesn't work, there are no errors whatsoever, but I can't even get the download dialog box to open:

Client Side

$scope.download=function(){
$http({method:'GET', url:'/download/'+image[0]['_id']}).
  success(function(data, status, headers, config) {         
    var element = angular.element('<a/>');
     element.attr({
         href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
         target: '_blank',
         download:'test.csv'
     })[0].click();
   }).
  error(function(data, status, headers, config) {
   });
  }

Server Side

app.namespace('/download/:documentID*', function() {

app.all('/', function(req, res, next){
  res.download('images/download/test.tif', 'test.tif', function(err){
  if (err) {
   } else {
     next();
      }
    });
  });
})

Upvotes: 3

Views: 4787

Answers (1)

nietonfir
nietonfir

Reputation: 4881

Last time I checked you couldn't trigger a download via ajax. ;-)

You'll need to create a <a> with e.g. target="_blank" so it opens up in a new tab/window. Don't know about your authentication though, I wouldn't send them in cleartext. You could work around that by checking the credentials in your ajax request and then open a new tab/window so that the file can be downloaded with some kind of one-time token. You'll need some server-side changes ofc.

Upvotes: 3

Related Questions