Download files via angular

Viewed 1115

I'm trying to make simple file server. I have Node.js backend with MongoDB GridFS storage to store files. I'm getting files from server by gridfs-stream. On the front-end I`m using Angular. And I have two major problems:

  1. When I'm using Blob to serve downloads, filename becomes: "d1c393df-b0d9-4ae5-befe-8d45b183eb54..." kind. I read a lot of docs about it and didn`t find any solutions.
  2. When I`m serving downloads only by Express without authentication, files load correctly. But I send auth info via Angular and without them application will throw the error. I can specify route without authentication but this makes my application unsafe.

I hope you help me to:

  1. Find another way to download files of any format.
  2. Change my existing code to get things work correctly

My Angular Service to get files by constructing a Blob:

getFilesFactory.download = function(filename){
  $http.get('/api/files/' + filename, {responseType:'arraybuffer'})
  .then(function(data){
    var stringCT = data.headers('Content-Type').toString();
    console.log(stringCT);
    var contentType = stringCT.substring(1, stringCT.length - 1);
    console.log(contentType);

      switch (contentType) {
        case "image/jpeg":
          file = new Blob([data.data], {type: 'image/jpeg'});
          fileURL = URL.createObjectURL(file);
          $window.open(fileURL);
        break;
        case "application/pdf":
          file = new Blob([data.data], {type: 'application/pdf'});
          fileURL = URL.createObjectURL(file);
          $window.open(fileURL);
        break;
        case "application/msword":
          file = new Blob([data.data], {type: 'application/msword'});
          fileURL = URL.createObjectURL(file);
          $window.open(fileURL);
        break;
        case "application/octet-stream":
          file = new Blob([data.data], {type: 'application/octet-stream'});
          fileURL = URL.createObjectURL(file);
          $window.open(fileURL);
        break;
        default: console.log("no contentType match");
      }
  });
};
1 Answers
Related