【问题标题】:Migrate GetObject (v2) to GetObjectCommand (v3) - aws-sdk将 GetObject (v2) 迁移到 GetObjectCommand (v3) - aws-sdk
【发布时间】:2022-01-01 03:38:51
【问题描述】:

我正在尝试将 Express 端点从 aws-sdk for JavaScript 的 v2 迁移到 v3。端点是 AWS S3 的文件下载器。

在版本 2 中,我将GetObject 的结果以可读流的形式传回浏览器。在版本 3 中,同样的技术失败并出现错误:

TypeError: data.Body.createReadStream 不是函数

如何处理从新 GetObjectCommand 返回的数据?它是一个斑点吗?我很难在v3 SDK docs 中找到任何有用的东西。

这是端点的两个版本:

import AWS from 'aws-sdk'
import dotenv from 'dotenv'

import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'

dotenv.config()

// VERSION 3 DOWNLOADER - FAILS
const getFileFromS3v3 = async (req, res) => {
  const client = new S3Client({ region: 'us-west-2' })
  const params = {
    Bucket: process.env.AWS_BUCKET,
    Key: 'Tired.pdf',
  }

  const command = new GetObjectCommand(params)

  try {
    const data = await client.send(command)
    console.log(data)
    data.Body.createReadStream().pipe(res)
  } catch (error) {
    console.log(error)
  } 
}

// VERSION 2 DOWNLOADER - WORKS
const getFileFromS3 = async (req, res) => {
  const filename = req.query.filename
  var s3 = new AWS.S3()
  var s3Params = {
    Bucket: process.env.AWS_BUCKET,
    Key: 'Tired.pdf',
  }

  // if the file header exists, stream the file to the response
  s3.headObject(s3Params, (err) => {
    if (err && err.code === 'NotFound') {
      console.log('File not found: ' + filename)
    } else {
      s3.getObject(s3Params).createReadStream().pipe(res)
    }
  })
}

export { getFileFromS3, getFileFromS3v3 }

【问题讨论】:

    标签: amazon-web-services express amazon-s3 aws-sdk


    【解决方案1】:

    此版本 3 代码有效。感谢major assist,诀窍是通过管道传递data.Body,而不使用任何fileStream 方法。

    import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
    import dotenv from 'dotenv'
    
    dotenv.config()
    
    const getFileFromS3 = async (req, res) => {
      const key = req.query.filename
      const client = new S3Client({ region: process.env.AWS_REGION })
      const params = {
        Bucket: process.env.AWS_BUCKET,
        Key: key,
      }
    
      const command = new GetObjectCommand(params)
    
      try {
        const data = await client.send(command)
        data.Body.pipe(res)
      } catch (error) {
        console.log(error)
      }
    }
    
    export { getFileFromS3 }
    

    当从这个前端函数调用时,上面的代码将文件从 S3 返回到浏览器。

      const downloadFile = async (filename) => {
        const options = {
          url: `/api/documents/?filename=${filename}`,
          method: 'get',
          responseType: 'blob',
        }
    
        try {
          const res = await axios(options)
          fileDownload(res.data, filename)
        } catch (error) {
          console.log(error)
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2022-10-21
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 2015-09-27
      • 2021-10-02
      • 1970-01-01
      • 2011-04-10
      相关资源
      最近更新 更多