通过角度下载文件

通过角度下载文件

问题描述:

我正在尝试制作简单的文件服务器。我有Node.js后端和MongoDB GridFS存储来存储文件。我通过gridfs-stream从服务器获取文件。在前端我使用Angular。我有两个主要问题:通过角度下载文件

  1. 当我使用的Blob服务下载,filename变成了: “d1c393df-b0d9-4ae5-BEFE-8d45b183eb54 ......” 之类的。我读了很多关于它的文档,但没有找到任何解决方案。
  2. 当我只通过Express下载服务而没有身份验证时,文件会正确加载。但我通过Angular发送授权信息,如果没有它们,应用程序会抛出错误。我可以指定没有身份验证的路由,但这会使我的应用程序不安全。

我希望你能帮我:

  1. 找到另一种方式来下载任何格式的文件。
  2. 将我现有的代码,把事情正常工作

我的角度服务通过构建一个斑点获得的文件:

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

你并不需要使用ajax下载文件并打开它在使用$window.open(fileURL);。您可以使用'/api/files/' + filename网址打开新窗口,浏览器将开始下载内容。您可以控制服务器端的Content-Type和文件名。你可以看看例子:Nodejs send file in response

+0

我使用这种技术时,没有Angular服务应用程序。但是当我实现它时,Express方法'res.redirect()'不工作(浏览器不打开任何链接,并且我的数据丢失了) 您能否提供示例? – stasinua