使用@aws-sdk/lib-storage上传文件到AWS S3时访问位置。

5

我目前正在将我的项目从SDK v2升级到V3的过程中,我正在努力访问我上传到S3存储桶的文件的位置URL。

目前,以下实现无法访问location,因为它不存在于AbortMultipartUploadCommandOutput响应类型中。

try {
    const x = new Upload({
      client: new S3Client({ region: "us-east-2" }),
      params: {
        Bucket: BUCKET_NAME,
        Key: filename.toString(),
        Body: buffer
      }
    })


    const response = await x.done()
    
    const locationUrl = response.location

    return locationUrl

  } catch (error) {
    console.log(error)
  }

我一直在探索的另一个解决方案是使用PutObjectCommand

const command = new PutObjectCommand({
    Bucket: BUCKET_NAME,
    Key: `${path}/${fileName}`,
    Body: fileContent,
    ContentType: "text/csv"
  })

一旦文件上传到S3上,有哪些可能的解决方案可以访问我的文件信息?


请查看以下链接:https://stackoverflow.com/questions/64980652/how-to-get-aws-s3-object-location-url-using-python-3-8实际上,您可能不需要输出URL,因为您可以自己构建它。 - karan shah
4个回答

2
你可以通过upload.done()返回的结果来缩小范围,并访问属性。
function isComplete(
    output:
      | CompleteMultipartUploadCommandOutput
      | AbortMultipartUploadCommandOutput,
  ): output is CompleteMultipartUploadCommandOutput {
    return (output as CompleteMultipartUploadCommandOutput).ETag !== undefined;
  }

const result = await upload.done();
if (isComplete(result)) {
  const key = result.Key;
  const location = result.Location;
}

1

const response = await x.done() return type is CompleteMultipartUploadCommandOutput| AbortMultipartUploadCommandOutput, Location details is returned in CompleteMultipartUploadCommandOutput you can do it like this

const response = await x.done() 的返回类型是 CompleteMultipartUploadCommandOutput| AbortMultipartUploadCommandOutput,位置详细信息在 CompleteMultipartUploadCommandOutput 中返回,您可以像这样处理它

      const data: CompleteMultipartUploadCommandOutput = await parallelUploads3.done();
      if (!data.Location) {
        throw new Error('Location not found');
      }
      return data.Location;
 

0

不要这样做,改为这样

客户

const config: S3ClientConfig = {
  region: "us-east-2",
  maxAttempts: 10,
  credentials: {
    accessKeyId: access_key_id,
    secretAccessKey: secret_access_key,
  },
};

export const s3 = () => new S3(config) || new S3Client(config);

上传功能
try {
    const x = new Upload({
client: s3(),
queueSize: 4,
leavePartsOnError: false,
params: {
  ACL: "public-read",
  ContentType: "image/jpeg",
  Key,
  Body: file,
  Bucket: AWS_S3_BUCKET_NAME,
},
})


    const response = await x.done()
    
    const locationUrl = response.location

    return locationUrl

  } catch (error) {
    console.log(error)
  }

-1
如果响应码是200,你可以自己创建。
location = https://${BUCKET_NAME}.s3.${AWS_REGION}.amazonaws.com/${Key}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接