Search code examples
javascriptangularjsnode.jsblobfilesaver.js

Is there a way to download any kind of file using angular filesaver?


I'm using node.js and angular.js for my app and I'm trying to download files through the browser using Blob and fileSaver.js.

I've used these in other sections of my app to download text files and pdf files specifying the correct type when creating the Blob object without any problem, but in the current section I need to support any type of file and I don't know if it's possible.

For example, I've tried downloading an image file with and without type:image/png and the result was a corrupted image - inspecting it in a text editor and comparing it with the original file shows that many of the bytes were changed.

Here are the code snippets I use:

Server:

fs.readFile(/* snipped file path */, function(err, data){
    if(err){
        /* handle error */
    }
    else{
        res.send(data);
    }
});

Client:

$http.get(/* endPoint URL */)
    .success(function(result){
        var data = new Blob([result], {type: 'image/png'});
        FileSaver.saveAs(data, filename);
    });

A few questions:

  1. Do I need to specify type for Blob? If so, do I need to specify it at server, too (it's a pain to determine it)? Can't I just skip it on both ends?
  2. What causes the image test to result in corrupted file? Am I missing some content-type header or something?

Solution

  • Try adding {contentType: 'arraybuffer'} to your GET request and remove type from Blob definition, like so:

    $http.get(/* endPoint URL */, {contentType: 'arraybuffer'})
      .success(function(result){
          var data = new Blob([result]);
          FileSaver.saveAs(data, filename);
      });
    

    (Edit: deleted redundant type definition from Blob)