1

I have an app with an Express backend, and angular frontend. I am trying to create a file download link for image files, but I am running into problems sending the file from express to angular. My angular looks like this...

  scope.download = function(file){
    http({method:'GET', url:'/get_download/' + file.id}).
       success(function(data, status, headers, config) {
         var element = angular.element('<a/>');
         element.attr({
             href: 'data:attachment;charset=utf-8,' + encodeURIComponent(data),
             target: '_self',
             download: file.name
         })[0].click();
       }).
      error(function(data, status, headers, config) {
        console.log("THERE WAS AN ERROR");
    });
  }

I have tried several different things on the express side each of which are producing different errors.

First I tried the following...

    res.download("my_file_path", "my_file_name", function (err) {
      if (err) {
        console.log("ERROR");
        console.log(err);
      }
    });

And got this error...

path.js:360
    throw new TypeError('Arguments to path.join must be strings');
    ^
TypeError: Arguments to path.join must be strings

Then I tried...

fs.readFile("my_file_path", function(err, data) {
   res.writeHead(200, { 'Content-disposition': 'attachment' });
   res.end(data);
});

Which downloaded the file, but it got corrupted along the way, and would not open. Any suggestions would be appreciated.

jherrlin
  • 11
  • 2
  • Did you try converting the file to base64 and sending that to the client (also changing the `charset` to `base64` in the client)? – mscdex Jan 07 '15 at 01:35
  • Take a look at this [question](http://stackoverflow.com/a/7288883/1470937). It shows an example that can help you. – hugohabel Jan 07 '15 at 01:39
  • In your route handler try using `res.setHeader('Content-Disposition', 'attachment');` and `res.send(data)` – teleaziz Jan 07 '15 at 03:16

0 Answers0