3

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();
      }
    });
  });
})

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

this is the html code in the template: <a ng-href="" target="_blank" type="button" class="btn btn-primary btn-lg btn-block" ng-click="download()">Download</a> isn't correct ?
@Cris69 Don't know, I'm not into angular. Basically yes, but you won't accomplish anything. href is empty and you still call your callback for the download. You can remove your ajax call and simply rewrite href dynamically. Imho that should get you going.
You are right the $http request is unnecessary, a simple <a ng-href="{{file}}" target="_self"></A> is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.