接收zip文件,angularJs

时间:2015-03-16 08:10:02

标签: angularjs rest download jersey zip

当我想从Rest api下载zip文件时,我遇到了问题,

当zip文件从我的服务器(带泽西)转移时,我收到它已损坏,...

我已经尝试将responseType: 'arraybuffer'放在我的$ http请求中,但它没有修复任何内容......这是我的代码。

$http.get(uploadUrl, {
           cache: false,
           responseType: 'arraybuffer'
      })
     .success(function (data, $scope) {
         var element = angular.element('<a/>');
         console.debug("data : " + data);
         element.attr({
             href: 'data:application/octet-stream;charset=utf-8,' + encodeURI(data),
             target: '_blank',
             download: fileName
         })[0].click();
      })
     .error(function () {
        console.info("fail on download");
      });
};

2 个答案:

答案 0 :(得分:1)

我过去遇到过这个问题。您还需要使用Buffer并触发打开“另存为”对话框,如下所述:

var url = (...)
var expectedMediaType = (...)

var requestData = (...)
$http.post(url, requestData, {
  params: {
    queryParam: 'queryParamValue'
  },
  headers: {
    'Content-Type': 'application/json',
    'Accept': expectedMediaType
  }
}).then(function (response) {
  var filename = (...)
  openSaveAsDialog(filename, response.data, expectedMediaType);
});

以下是openSaveAsDialog函数的内容:

function openSaveAsDialog(filename, content, mediaType) {
  var blob = new Blob([content], {type: mediaType});
  saveAs(blob, filename);
}

要使用saveAs功能,您需要包含https://github.com/eligrey/FileSaver.js库。要安装它,只需使用HTML页面中的标记脚本引用其js文件。

<script src="js/FileSaver.js"></script>

我写了一篇博客文章,描述了如何修复它:https://templth.wordpress.com/2014/11/21/handle-downloads-with-angular/

希望它能帮到你, 亨利

答案 1 :(得分:0)

我正在以相同的方式下载zip($ http / arrayBuffer)并且它可以工作。

我猜这个问题来自:

encodeURI(data)

我认为你应该在base64中对它进行编码(那里有大量的例子,如https://github.com/niklasvh/base64-arraybuffer/blob/master/lib/base64-arraybuffer.js

相关问题