简体   繁体   English

使用 jQuery 下载 .gz 文件

[英]Download a .gz file using jQuery

I have to call a remote service to download a gzipped file (csv.gz).我必须调用远程服务来下载一个 gzipped 文件 (csv.gz)。 I have to use jQuery because I have to set the Authentication HTTP header.我必须使用 jQuery,因为我必须设置身份验证 HTTP 标头。 I tried with something like this:我试过这样的事情:

$.ajax({
                type: "GET",
                url: url
            }).done(function (res) {
                const a = document.createElement('a');
                a.style = 'display: none';
                document.body.appendChild(a);
                const blob = new Blob([res]);
                const url = URL.createObjectURL(blob);
                a.href = url;
                a.download = _this.attributes.id + '.' + _DEFAULT_DOWNLOADED_FILE_EXTENTION;
                a.click();
                URL.revokeObjectURL(url);
            }).fail(function (err) { });

I'm able to download the file but, after the download, I tried to unzip it on my pc but the file is not correct (corrupted).我可以下载该文件,但下载后,我尝试将其解压缩到我的电脑上,但该文件不正确(已损坏)。 Probably the Blob creation that I used it's not correct.可能我使用的 Blob 创建不正确。

You're trying to download binary data, you can fetch it using typed arrays in JavaScript, here 's an example in the MDN.您正在尝试下载二进制数据,您可以使用 JavaScript 中的类型化数组获取它, 是 MDN 中的示例。

In regards to setting the Authentication header, you don't need jQuery for that.关于设置身份验证标头,您不需要 jQuery。 Here 's the XHR API that enables you to do it. 是使您能够执行此操作的 XHR API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM