Client download of a server generated zip file

后端 未结 4 1049
傲寒
傲寒 2020-12-16 21:17

Before somebody says, \"duplicate\", I just want to make sure, that folks know, that I have already reviewed these questions:

1) Uses angular and php, not sure what

4条回答
  •  爱一瞬间的悲伤
    2020-12-16 21:45

    As indicated in this answer, I have used the below Javascript function and now I am able to download the byte[] array content successfully.

    Function to convert byte array stream (type of string) to blob object:

    var b64toBlob = function(b64Data, contentType, sliceSize) {
          contentType = contentType || '';
          sliceSize = sliceSize || 512;
    
          var byteCharacters = atob(b64Data);
          var byteArrays = [];
    
          for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);
    
            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
              byteNumbers[i] = slice.charCodeAt(i);
            }
    
            var byteArray = new Uint8Array(byteNumbers);
    
            byteArrays.push(byteArray);
          }
    
          var blob = new Blob(byteArrays, {type: contentType});
          return blob;
    };
    

    An this is how I call this function and save the blob object with FileSaver.js (getting data via Angular.js $http.get):

        $http.get("your/api/uri").success(function(data, status, headers, config) {
            //Here, data is type of string
            var blob = b64toBlob(data, 'application/zip');
            var fileName = "download.zip";
            saveAs(blob, fileName);
        });
    

    Note: I am sending the byte[] array (Java-Server-Side) like this:

    byte[] myByteArray = /*generate your zip file and convert into byte array*/ new byte[]();
    return new ResponseEntity(myByteArray , headers, HttpStatus.OK);
    

提交回复
热议问题