Receive zip file, angularJs

2019-03-06 18:15发布

I've got a problem when I want to download a zip file from a Rest api,

When the zip file is tranfered from my server (with jersey), I receive it corrupted, ...

I've already tried to put responseType: 'arraybuffer' on my $http request but it isn't fixing anything... here's my code.

$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条回答
相关推荐>>
2楼-- · 2019-03-06 18:36

I'm downloading zip in the same way ($http / arrayBuffer) and it works.

I would guess that the problem come from :

encodeURI(data)

I think you should encode it in base64 (there is tons of exemples out there like https://github.com/niklasvh/base64-arraybuffer/blob/master/lib/base64-arraybuffer.js )

查看更多
男人必须洒脱
3楼-- · 2019-03-06 18:50

I encountered this problem in the past. You need to use the Buffer as well and trigger the opening of the "Save As" dialog, as described below:

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

Here is the content of the openSaveAsDialog function:

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

To use the saveAs function, you need to include https://github.com/eligrey/FileSaver.js library. To install it, just reference its js file using a tag script in your HTML page.

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

I wrote a blog post describing how to fix it: https://templth.wordpress.com/2014/11/21/handle-downloads-with-angular/.

Hope it will help you, Thierry

查看更多
登录 后发表回答