Use a base64 preview of binary data response (zip file) in angularjs

I always get this error in the downloaded zip file C:\Users\me\Downloads\test.zip: Unexpected end of archive

My current code is:

var blob = new Blob([data], { // data here is the binary content
    type: 'octet/stream',
});
var zipUrl = window.URL.createObjectURL(blob);
var fileName = orderNo;
fileName += '.zip';
downloadFile(null, fileName, null, zipUrl, null); // just creates a hidden anchor tag and triggers the download

The call response is binary (I think). Binary content here

But the preview is base64. Base64 content . And it is right. I check this using fiddle .

You can refer to the network screenshot here

I put the contents of base64 on this line var sampleBytes = base64ToArrayBuffer('');And the downloaded zip just opens perfectly.

Things I've tried so far.

  • Adding these headers to the GET call

    headers var = {Accept: application / octet stream, responseType: 'blob',}; But I getRequest header field responseType is not allowed by Access-Control-Allow-Headers in preflight response.

ajax.service.js AngularJS.

var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"}); var fileName = "myFileName.myExtension"; saveAs(blob, fileName);

, , . , .

. preview base64 . ? ( , ), binary to base64, .

0
1

, , ajax.service.js, , .

xhr . , : auth.

.

:

fetchBlob(url, function (blob) {
    // Array buffer to Base64:
    var base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(blob)));
    var blob = new Blob([base64ToArrayBuffer(base64)], {
        type: 'octet/stream',
    });
    var zipUrl = window.URL.createObjectURL(blob);
    var fileName = orderNo;
    fileName += ' Attachments ';
    fileName += moment().format('DD-MMM-YYYY');
    fileName += '.zip';
    downloadFile(null, fileName, null, zipUrl, null); // create a hidden anchor tag and trigger download
});

function fetchBlob(uri, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', uri, true);
    xhr.responseType = 'arraybuffer';
    var x = AjaxService.getAuthHeaders();
    xhr.setRequestHeader('auth_stuff', x['auth_stuff']);
    xhr.setRequestHeader('token_stuff', x['token_stuff']);
    xhr.setRequestHeader('Accept', 'application/octet-stream');

    xhr.onload = function (e) {
        if (this.status == 200) {
            var blob = this.response;
            if (callback) {
                callback(blob);
            }
        }
    };

    return xhr.send();
};

function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    };

    return bytes;
}
0

Source: https://habr.com/ru/post/1648255/


All Articles