4

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");
      }
  });
};
mscdex
  • 104,356
  • 15
  • 192
  • 153
stasinua
  • 59
  • 6

1 Answers1

0

You don't need to use ajax for downloading file and opening it in using $window.open(fileURL);. You can just open new window with '/api/files/' + filename url and browser will start to download content. And you can control Content-Type and file name on a server side. You can take a look on example: Nodejs send file in response

Community
  • 1
  • 1
Timur Bilalov
  • 3,522
  • 1
  • 16
  • 14
  • I`m using that technique when serve app without Angular. But when I implement it, Express method 'res.redirect()' not working(browser don`t open any links. And my data lost) Can you provide example? – stasinua Mar 08 '16 at 10:59