在没有任何插件的reactjs中下载zip文件

qaz*_*qaz 1 zip gzip reactjs

我收到来自rest api的响应,其Content-Typeistext/htmlContent-Encodingis gzip

我尝试使用 blob 下载它

const blob = new Blob([res], { type: 'application/gzip' });
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement('a'); 
a.href = downloadUrl;
document.body.appendChild(a);
a.click();
Run Code Online (Sandbox Code Playgroud)

但下载的 gz 文件无法打开(似乎已损坏)。有人可以帮我下载 .zip 文件吗reactjs

编辑:需要一个不使用任何外部插件的解决方案

Dee*_*kar 5

你可以使用jszipnpm 模块。

例如:

var zip = new JSZip();

zip.file("Hello.txt", "Hello World\n");
var img = zip.folder("images"); //images is the folder which will be zip

img.file("smile.gif", imgData, {base64: true});

zip.generateAsync({type:"blob"}).then(function(content) {

    saveAs(content, "example.zip");
});
Run Code Online (Sandbox Code Playgroud)

要在没有 jszip 的情况下使用它,您可以尝试以下代码:

function str2bytes (str) {
    var bytes = new Uint8Array(str.length);
    for (var i=0; i<str.length; i++) {
        bytes[i] = str.charCodeAt(i);
    }
    return bytes;
}
Run Code Online (Sandbox Code Playgroud)

及其用法:

var blob = new Blob([str2bytes(myData)], {type: "application/zip"});
saveAs(blob, "data.zip"); 
Run Code Online (Sandbox Code Playgroud)

但这jszip是一种更好的替代方法。


归档时间:

查看次数:

21282 次

最近记录:

3 年,7 月 前