首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将GetObject (v2)迁移到GetObjectCommand (v3) -aws

将GetObject (v2)迁移到GetObjectCommand (v3) -aws
EN

Stack Overflow用户
提问于 2022-01-01 03:38:51
回答 1查看 1.2K关注 0票数 1

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

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

TypeError: data.Body.createReadStream不是一个函数

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

以下是端点的两个版本:

代码语言:javascript
运行
复制
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 }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-01 05:14:13

这个版本3的代码可以工作。由于有了主要协助,诀窍是通过管道输送data.Body,而不使用任何fileStream方法。

代码语言:javascript
运行
复制
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返回到浏览器。

代码语言:javascript
运行
复制
  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)
    }
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70546841

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档