通过角度下载文件

时间:2016-03-07 20:32:25

标签: javascript angularjs node.js

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

  1. 当我使用Blob进行下载时,filename变为:" d1c393df-b0d9-4ae5-befe-8d45b183eb54 ......"类。我阅读了很多关于它的文档,并没有找到任何解决方案。
  2. 当我只通过Express进行下载而不进行身份验证时,文件会正确加载。但我通过Angular发送auth信息,没有它们应用程序将抛出错误。我可以在没有身份验证的情况下指定路由,但这会使我的应用程序不安全。
  3. 我希望你帮助我:

    1. 找到另一种下载任何格式文件的方法。
    2. 更改现有代码以使工作正常
    3. My Angular Service通过构建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 个答案:

答案 0 :(得分:0)

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

相关问题