You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级AWS SDK v2至v3后,如何获取S3上传文件的Location URL?

解决AWS SDK v3获取S3上传文件Location URL的方案

一、使用PutObjectCommand的场景

PutObjectCommand的响应中自带Location字段,直接从返回结果中提取即可,示例代码:

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3Client = new S3Client({ region: "你的区域" });

async function uploadFile() {
  const params = {
    Bucket: "你的存储桶名",
    Key: "文件存储路径/文件名",
    Body: 文件内容
  };

  const command = new PutObjectCommand(params);
  const response = await s3Client.send(command);
  
  // 直接获取Location
  const fileLocation = response.Location;
  console.log(fileLocation);
}

注:如果存储桶使用自定义域名或S3加速域名,需根据实际配置调整Location格式。

二、使用@aws-sdk/lib-storage Upload类的场景

Upload类完成分块上传后不会直接返回Location,可通过两种方式获取:

方法1:手动构造Location URL

根据存储桶名、区域和文件Key直接拼接,这是最直接可靠的方式:

const bucketName = "你的存储桶名";
const region = "你的区域";
const fileKey = "文件存储路径/文件名";

// 标准S3访问地址格式
const fileLocation = `https://${bucketName}.s3.${region}.amazonaws.com/${fileKey}`;

// 若使用静态网站托管域名,替换为对应前缀即可

方法2:调用HeadObjectCommand验证并构造

如果需要同时验证文件上传状态、获取ETag等元数据,可先调用HeadObjectCommand,再构造Location:

import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";

const s3Client = new S3Client({ region: "你的区域" });

async function uploadLargeFile() {
  const uploadParams = {
    client: s3Client,
    params: {
      Bucket: "你的存储桶名",
      Key: "文件存储路径/文件名",
      Body: 大文件内容
    }
  };

  const upload = new Upload(uploadParams);
  await upload.done(); // 完成分块上传

  // 验证文件存在并获取元数据
  const headCommand = new HeadObjectCommand({
    Bucket: uploadParams.params.Bucket,
    Key: uploadParams.params.Key
  });
  const headResponse = await s3Client.send(headCommand);

  // 构造Location
  const fileLocation = `https://${uploadParams.params.Bucket}.s3.${s3Client.config.region}.amazonaws.com/${uploadParams.params.Key}`;
  console.log("文件地址:", fileLocation, "ETag:", headResponse.ETag);
}

三、注意事项

  • 若存储桶启用静态网站托管,Location需使用静态网站域名拼接,而非标准S3域名。
  • 确保IAM权限允许执行PutObject(上传操作)和HeadObject(若使用方法2)。
  • 若通过预签名URL上传,S3不会返回Location,手动构造是唯一可行方案。

内容的提问来源于stack exchange,提问作者Jamie Hunt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:37:03