简体   繁体   English

将 zip 文件从 node.js 服务器发送到 node.js 客户端

[英]Send zip file from node.js server to node.js client

I am trying to send a zip file from a node.js server to a node.js client but when i save the zip it is corrupted and will not open.我正在尝试将 zip 文件从 node.js 服务器发送到 node.js 客户端,但是当我保存 ZADCDBD79A8D84175C229B 时,它已损坏且不会打开 AADCDBD79A8D84175C229B1

I am using adm-zip to zip the file and send to client我正在使用 adm-zip 到 zip 文件并发送给客户端

app.get('/checkForUpdate', function (req, res) {

    var zip = new AdmZip();
    zip.addLocalFile("./update.js");
    var willSendthis = zip.toBuffer();
    res.send(willSendthis);

});

here is my client code这是我的客户代码

$.ajax({
    type: 'GET',
    contentType: 'application/json',
    data: {version: version},
    url: 'http://localhost:3000/checkForUpdate',
    success: function (data) {

        fs.writeFile("update.zip", data, function(err) {

            if(err) {
                console.log(err);
            } else {
                console.log("The file was saved!");
            }

        });
    }
});

我猜应该为MIME类型application/x-zip-compressed

I think the issue is sending a buffer. 我认为问题正在发送缓冲区。 If I remember right a buffer needs a mime type of octect-stream. 如果我没记错的话,缓冲区需要一个MIME类型的octect流。 Try using octect-stream in the header and have adm-zip load the buffer 尝试在标头中使用octect-stream并让adm-zip加载缓冲区

If you want to compress a text or any data as a zip file you can use JSZip npm package.如果要将文本或任何数据压缩为 zip 文件,可以使用 JSZip npm package。

I have given the link below to install it.我已经给出了下面的链接来安装它。

https://www.npmjs.com/package/jszip https://www.npmjs.com/package/jszip

The code below converts the text file and sends it as a buffer that the client can download.下面的代码转换文本文件并将其作为客户端可以下载的缓冲区发送。

const zip = new JSZip()
zip.file("Hello.txt", "Hello World\n")
const buffer = await zip.generateAsync({ type: `nodebuffer` })
res.writeHead(200,{ 'Content-Type': `application/zip` })
res.end(buffer)

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

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