使用 Nextjs 中的 API 路由从 AWS s3 下载可读图像

Ahm*_*yes 2 download amazon-s3 next.js

我正在使用 Nextjs 来构建我的应用程序。我正在使用 AWS s3 来存储我的静态文件(图像和 PDF,..)

我希望我的应用程序的用户能够下载该文件。我使用此处提到的答案来开发解决方案,它有效,但图像不可读。表明

我们似乎不支持此文件格式

这是我的脚本:

// /pages/api/getFile.js
import { NextApiRequest, NextApiResponse } from "next";
import stream from 'stream';
import { promisify } from 'util';
import s3 from "../../../../utils/s3-utils";
const pipeline = promisify(stream.pipeline);

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const bucketName = process.env.S3_UPLOAD_BUCKET || ""

  const imageKey: any = req.query.imgkey

  const downloadParams = {
    Key: imageKey,
    Bucket: bucketName
  }

  const downloadedObject = await s3.getObject(downloadParams).promise()
  const readableFile= downloadedObject.Body?.toString('base64') || ""
  const fileType= downloadedObject.ContentType || ''

  res.setHeader('Content-Type', fileType);
  res.setHeader('Content-Disposition', `attachment; filename=${imageKey}`);
  await pipeline(readableFile, res);
}
Run Code Online (Sandbox Code Playgroud)

来自客户:

<a href="/api/getFile">Download PDF</a>
Run Code Online (Sandbox Code Playgroud)

知道这里出了什么问题吗?

Ahm*_*yes 5

答案如下:我能够通过使用createReadStream()正确的响应标头来使用和管道响应流来简单地解决这个问题

import s3 from "../../../../utils/s3-utils";

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const bucketName = process.env.S3_UPLOAD_BUCKET || ""
  const imageKey: string = req.query.imgkey.toString()
  const imageFormat = imageKey.split(".")[1]

  const downloadParams = {
    Key: imageKey,
    Bucket: bucketName
  }

  const readableObject = s3.getObject(downloadParams).createReadStream()

  res.setHeader('Content-Type', `image/${imageFormat}`);
  res.setHeader('Content-Disposition', `attachment; filename=${imageKey}`);
  readableObject.pipe(res)
}
Run Code Online (Sandbox Code Playgroud)