How to download a zip file in AngularJS / FilesaverJS [duplicate]

浪子不回头ぞ 提交于 2019-12-02 10:28:56

You should have 2 separate rest services on backend for this so instead of serving all files at the same time and holding them in browser, you should retrieve list of available files from one rest endpoint and then on user's click retrieve specific file from another rest endpoint. Your service for file could look something like this:

function downloadFile(src) {
  let header, startIndex, filename;
  $http({
    method: 'GET',
    url: src,
    headers: {
      'Accept': 'text/html,application/xhtml+xml,application/xml,application/pdf;q=0.9,image/webp,*/*;q=0.8',
      'Upgrade-Insecure-Requests': 1
    },
    responseType: 'blob'
  }).then(function (successResponse) {
    header = unescape(successResponse.headers()['content-disposition']);
    startIndex = header.indexOf('filename=');
    filename = header.slice(startIndex + 10,-1);
    try{
      saveAs(successResponse.data, filename);
    }
    catch(error){
      // FileSaver error
    }
  }, function (errorResponse) {
    // Server error has occurred during file downloading.
}

Where you need to specify response type to be blob. Variable src in this example would be specific endpoind serving desired file (here it's served from controller based on data retrieved from list of files available but you can build it here if you want based on file's id or something). In this case backend is serving full file name in exposed header so you can extract it and save file with it's proper name and format. Extraction in this example was for specific rest response but you should be able to change it to suite your needs.

Example: content disposition header would be string, something like:

Content-Disposition: attachment; filename="picture.png"

In this case service would extract that name and Filesaver would save file "picture.png".

How to download a zip file in AngularJS

To download a binary file type such as a zip file, it is important to set the responseType before doing the XHR.

var config = { responseType: "blob" };

var promise = $http.get(url, config);

promise
  .then(function onSuccess(response) {
    // Handle success
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    ...
  }).catch(function onError(response) {
    // Handle error
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    ...
  });

For more information, see MDN Web API Reference - XHR responseType.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!