简体   繁体   中英

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. 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.

I think your problem is that you're doing toString('base64') there. 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.

This makes me believe that it actually means that AWS will automatically convert your (non-base64) body into base64 in the response body. If that's the case, due to you doing .toString('base64') , your body is being base64'd twice. You could un-base64 your resulting file.zip and see what it gives.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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