【问题标题】:How to download a file .zip instead of a binary in JS?如何在 JS 中下载文件 .zip 而不是二进制文件?
【发布时间】:2022-01-16 14:37:48
【问题描述】:

我正在尝试构建一个简单的网站,其后端使用 NodeJS + ExpressJS 构建,允许用户从客户端下载一些 ZIP 文件。

但是我在Postman中测试逻辑时,返回的数据是一串符号,说明是二进制文件,不是.zip文件。

这里是sn-p的代码:

app.post('/', (req, res) => {
    try {
        const { specialID } = req.body;

    if (!specialID) {
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        return res.end('specialID needs to be specified');
    }

    const specialIDsMap = {
        one: 1,
        22: 2,
        '33threee': 3,
    };
    const targetFile = specialIDsMap[specialID];
    const filePath = `./zips/${targetFile}.zip`;
    const fileName = 'test-file.zip';


 fs.exists(filePath, (exists) => {
            if (exists) {
                res.writeHead(200, {
                    'Content-Type': 'application/octet-stream',
                    'Content-Disposition': 'attachment; filename=' + fileName,
                });
                fs.createReadStream(filePath).pipe(res);
            } else {
                res.writeHead(400, { 'Content-Type': 'text/plain' });
                res.end('ERROR File does not exist');
            }
        });

我必须做些什么来确保服务器给我的是 .zip 文件而不是二进制文件?

【问题讨论】:

    标签: node.js express fs content-type content-disposition


    【解决方案1】:

    这是因为您的文件不是压缩文件,考虑使用ArchiverJs 可能会解决您的问题。

    代码示例:

    res.writeHead(200, {
          'Content-Type': 'application/zip',
          'Content-disposition': 'attachment; filename='+fileName  
    });
    
    let zip = Archiver('zip');
    zip.pipe(res);
    
    zip.file(filePath , { name: fileName  })
            .finalize();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2012-11-23
      • 2016-03-17
      • 1970-01-01
      相关资源
      最近更新 更多