简体   繁体   English

在 aws laba node.js 中从 s3 提供 zip 文件 - 下载后无法提取

[英]Serving zip file from s3 in aws lamba node.js - unable to extract after download

I'm trying to create a lambda function to read a zip file from s3 and to serve it.我正在尝试创建一个 lambda 函数来从 s3 读取 zip 文件并为其提供服务。 But after downloading this file in the browser I can't unzip it, getting the error "Unable to extract, it is in an unsupported format".但是在浏览器中下载此文件后,我无法解压缩,出现错误“无法提取,格式不受支持”。 What can be a problem?有什么问题?

const file = await s3.getObject({ 
        Bucket: 'mybucket', 
        Key: `file.zip` 
    }).promise();

return {
    statusCode: 200,
    isBase64Encoded: true,
    body: Buffer.from(file.Body).toString('base64'),
    headers: {
        'Content-Type': 'application/zip',
        'Content-Disposition': `attachment; filename="file.zip"`,
    },
}

Your file.Body should already be a Buffer, so Buffer.from(file.Body) should be unnecessary but unharmful.你的file.Body应该已经是一个缓冲区,所以Buffer.from(file.Body)应该是不必要的但无害的。

I think your problem is that you're doing toString('base64') there.我认为你的问题是你在那里做toString('base64') The documentation says: 文档说:

If body is a binary blob, you can encode it as a Base64-encoded string by setting isBase64Encoded to true and configuring / as a Binary Media Type.如果 body 是二进制 blob,您可以通过将 isBase64Encoded 设置为 true 并将/配置为二进制媒体类型,将其编码为 Base64 编码的字符串。

This makes me believe that it actually means that AWS will automatically convert your (non-base64) body into base64 in the response body.这让我相信这实际上意味着 AWS 会在响应正文中自动将您的(非 base64)正文转换为 base64。 If that's the case, due to you doing .toString('base64') , your body is being base64'd twice.如果是这种情况,由于您执行了.toString('base64') ,您的身体将被 base64'd 两次。 You could un-base64 your resulting file.zip and see what it gives.您可以取消 base64 生成的file.zip并查看它提供了什么。

我的解决方案是设置 'Content-Encoding': 'base64' 响应头。

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

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