首页 > 解决方案 > 无法从 Node.js (express) 服务返回 xlsx 文件,该服务从 S3 存储桶获取该文件以供浏览器应用程序使用

问题描述

在 Excel 中创建了一个 xlsx 文件,通过控制台从桌面手动上传到 AWS S3。现在想要向 Node.js 快速服务添加一个端点,该服务将从 S3 检索该文件并将其传递回 javascript 浏览器应用程序。

纯文本文件似乎很好,但不断为 xlsx 文件(甚至在 Excel 中创建的 csv)获取 HTTP 状态代码 500。

尝试了以下变化:

res.send(s3.getObject().toString()); //this works with plain text file
res.send(s3.getObject().toString('utf-8'));
res.send(s3.getObject().toString('binary'));

这些都没有运气,调用立即失败,出现 500 内部服务器错误。

标签: javascriptnode.jsamazon-web-servicesexpressamazon-s3

解决方案


就像是

    s3.headObject(params, 
        (err, data)=>{
            if (err) {
                  return res.status(500).end(err.message);
            }
            // Add the content type to the response (it's not propagated from the S3 SDK)
            res.set({
                'Content-Type': data.ContentType,
                'Content-Length': data.ContentLength,
                'Last-Modified': data.LastModified,
                'ETag': data.ETag
            });
            s3.getObject(params).createReadStream().pipe(res)
        }
    );

推荐阅读