Receive zip file, angularJs

后端 未结 2 1393
夕颜
夕颜 2021-01-29 09:17

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, ...

相关标签:
2条回答
  • 2021-01-29 09:37

    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

    0 讨论(0)
  • 2021-01-29 09:41

    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 )

    0 讨论(0)
提交回复
热议问题