【问题标题】:Downloading Zip file using angular-js and django使用 angular-js 和 django 下载 Zip 文件
【发布时间】:2015-04-30 06:08:44
【问题描述】:

我正在尝试从我的 Django 视图中下载一个 Zip 文件。但是我正在通过发布请求从我的 angularjs 服务调用视图函数。视图正在返回一个 zip 文件,但它没有被下载。 谁能告诉我 angularjs 服务中 .success 函数的内容是什么,以便下载 zip 文件?

【问题讨论】:

    标签: django angularjs


    【解决方案1】:

    这个解决方案对我来说效果很好。希望对您有所帮助。

    var req = {
            method: 'POST',
            url: 'api/cdr/downloads/',
            responseType:"arraybuffer",
            data: selected
          };
    
          $http(req)
            .success(function(data, status, headers){
              var arr = data;
              var byteArray = new Uint8Array(arr);
              var a = window.document.createElement('a');
    
              a.href = window.URL.createObjectURL(
                new Blob([byteArray], { type: 'application/octet-stream' })
              );
              a.download = headers('filename');
    
              // Append anchor to body.
              document.body.appendChild(a);
              a.click();
    
    
              // Remove anchor from body
              document.body.removeChild(a);
            }
          ).error(function(){
            }
          );
    

    【讨论】:

      【解决方案2】:

      此处发布的答案对我不起作用。以下是最终对我有用的东西:

      在您的 javascript 中:

            $http({
                      url: "/serveZip",
                      method: 'POST',
                      responseType: 'arraybuffer'
                  }).then(function success(response){
                          var a = document.createElement('a');
                          var blob = new Blob([response.data], {'type':"application/zip"});
                          a.href = URL.createObjectURL(blob);
                          a.download = "myZip.zip";
                          a.click();
                          });
      

      在你的views.py中:

      def serveZip(request):
          zipPath = "path/to/myZip.zip"
          servableZip = open(zipPath,'rb')
          response = HttpResponse(servableZip, content_type='application/zip') 
          response['Content-Disposition'] = 'attachment; filename="myZip.zip"'
          return response
      

      这在 chrome 中对我有用,在其他地方没有尝试过,但如果它在其他浏览器中不起作用,你可以尝试 application/octet-stream 而不是 application/zip。

      【讨论】:

        猜你喜欢
        • 2017-10-22
        • 2015-10-18
        • 2020-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-07
        • 1970-01-01
        相关资源
        最近更新 更多