如何使用Javascript aws-sdk v3获取S3上传对象的访问URL
方案1:使用@aws-sdk/lib-storage的Upload类(最贴近v2原有逻辑)
v3版本把v2内置的upload方法抽离到了独立的@aws-sdk/lib-storage包中,该方法的返回值和v2保持一致,直接携带Location属性,同时还支持大文件分块上传,是官方推荐的替代方案。
首先安装依赖:
npm install @aws-sdk/client-s3 @aws-sdk/lib-storage
使用示例:
import { S3Client } from "@aws-sdk/client-s3"; import { Upload } from "@aws-sdk/lib-storage"; const s3Client = new S3Client({ region: "你的AWS区域" }); const upload = new Upload({ client: s3Client, params: { Body: body, Bucket: bucket, Key: key, ContentType: contentType, } }); const res = await upload.done(); // 直接获取公开访问URL return res.Location;
方案2:基于SDK内置的端点解析能力生成URL(仅使用PutObjectCommand场景)
如果你确定只需要上传小文件,不需要分块上传能力,不想引入额外依赖,可以使用SDK内置的端点解析逻辑生成URL,避免手动拼接导致的区域、分区(如AWS中国区、GovCloud)、访问风格(虚拟主机/路径模式)不兼容问题。
使用示例:
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; import { getEndpointFromInstructions } from "@aws-sdk/util-endpoints"; const s3Client = new S3Client({ region: "你的AWS区域" }); const command = new PutObjectCommand({ Body: body, Bucket: bucket, Key: key, ContentType: contentType, }); // 执行上传 await s3Client.send(command); // 利用SDK内置逻辑解析S3访问端点 const endpoint = await getEndpointFromInstructions( command.input, S3Client.serviceId, s3Client.config ); // 拼接对象Key生成最终访问URL const objectUrl = new URL( `${endpoint.url.pathname.replace(/\/$/, "")}/${key.replace(/^\//, "")}`, endpoint.url ).href; return objectUrl;
补充说明
v2版本upload方法返回的Location本身就是SDK在客户端拼接生成的,AWS S3服务端的PutObject接口本身不会返回对象访问URL。v3版本把这部分拼接逻辑从核心的PutObjectCommand中剥离,仅保留在Upload类中,所以原生PutObjectCommand的返回值没有Location字段。
内容的提问来源于stack exchange,提问作者Carter
相关产品推荐
相关产品推荐

