使用 Javascript 'aws-sdk' v3 获取上传的对象 URL

gum*_*ins 9 amazon-s3 aws-sdk aws-sdk-nodejs aws-sdk-js

目前我们使用的是aws-sdkv2,通过这种方式提取上传的文件URL

  const res = await S3Client
    .upload({
      Body: body,
      Bucket: bucket,
      Key: key,
      ContentType: contentType,
    })
    .promise();

  return res.Location;
Run Code Online (Sandbox Code Playgroud)

现在我们要升级到aws-sdkv3,新的文件上传方式如下所示

const command = new PutObjectCommand({
  Body: body,
  Bucket: bucket,
  Key: key,
  ContentType: contentType,
});

const res = await S3Client.send(command);
Run Code Online (Sandbox Code Playgroud)

不幸的是,res对象现在不包含Location属性。

getSignedUrlSDK功能看起来不太合适,因为它只是生成一个带有到期日期的URL(可能可以将其设置为一些额外的巨大持续时间,但无论如何,我们仍然需要有可能分析URL路径)

对我来说,手动构建 URL 看起来不是一个好主意,也不是一个稳定的解决方案。

gum*_*ins 8

回答自己:我不知道是否存在更好的解决方案,但我是这样做的

const command = new PutObjectCommand({
  Body: body,
  Bucket: bucket,
  Key: key,
  ContentType: contentType,
});

const [res, region] = await Promise.all([
  s3Client.send(command),
  s3Client.config.region(),
]);

const url = `https://${bucket}.s3.${region}.amazonaws.com/${key}`
Run Code Online (Sandbox Code Playgroud)

  • 这看起来像是对 SDK v2 的倒退。他们是否强迫我们发出额外的请求来获取官方对象 URL? (2认同)
  • @aghidini这取决于您是否需要虚拟托管或路径样式的URL https://docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html (2认同)