使用AWS SDK(S3.putObject)将可读流上传到S3(node.js)

问题描述 投票:0回答:2

我的目标是将

Readable
流上传到 S3。

问题是 AWS api 似乎只接受

ReadStream
作为流参数。

例如,以下代码片段就可以正常工作:

const readStream = fs.createReadStream("./file.txt") // a ReadStream

await s3.putObject({
    Bucket: this.bucket,
    Key: this.key,
    Body: readStream,
    ACL: "bucket-owner-full-control"
}

当我尝试用

Readable
ReadStream
扩展
stream.Readable
)做同样的事情时,问题就开始了。

以下代码片段失败了

const { Readable } = require("stream")
const readable = Readable.from("data data data data") // a Readable

await s3.putObject({
    Bucket: this.bucket,
    Key: this.key,
    Body: readable,
    ACL: "bucket-owner-full-control"
}

我从AWS sdk得到的错误是:

NotImplemented: A header you provided implies functionality that is not implemented

*** 请注意,我更喜欢

Readable
而不是
ReadStream
,因为我希望允许传递不一定源自文件的流(例如内存中的字符串)。 因此,可能的解决方案是将
Readable
转换为
Readstream
以与 SDK 配合使用。

任何帮助将不胜感激!

javascript node.js amazon-s3 stream
2个回答
3
投票

鉴于

Readable
不再是包含 MIME 类型和内容长度等元数据的文件,您需要更新
putObject
以包含这些值:

const { Readable } = require("stream")
const readable = Readable.from("data data data data") // a Readable

await s3.putObject({
    Bucket: this.bucket,
    Key: this.key,
    Body: readable,
    ACL: "bucket-owner-full-control",
    ContentType: "text/plain",
    ContentLength: 42 // calculate length of buffer
}

希望有帮助!


0
投票

计算长度并使用 Buffer 的示例:

import { Readable } from "stream";

  saveCreativeImage(name: string, image: Buffer): Promise<string> {
    const options: PutObjectRequest = {
      ACL: 'bucket-owner-full-control',
      Bucket: EnvConfig.S3_CREATIVES_BUCKET_NAME,
      Key: name,
      Body:  Readable.from(image),
      ContentType: 'image/png',
      ContentLength: image.length
    };

请注意,您过去可以直接发送 Buffer,但现在我认为需要 StreamingBlobTypes。其定义如下: https://github.com/awslabs/smithy-typescript/blob/21ee16a06dddf813374ba88728c68d53c3674ae7/packages/types/src/streaming-payload/streaming-blob-common-types.ts#L22

我认为这里已经改变了: https://github.com/aws/aws-sdk-js-v3/commit/96938415e65ccc4353be8f816e919215de12a1b7#diff-252b2f214c37b3c487fd068bff4968eaa1c8a6085dc9eba0d7bfe15239 b05094

© www.soinside.com 2019 - 2024. All rights reserved.