如何使用AWS SDK版本3获取上传到S3的文件的公共url



在AWS SDK版本2中,我将文件上传到S3,并在reponse中获取它们的公共url。

// using ASW SDK version 2
var S3 = require('aws-sdk/clients/s3')
var s3 = new S3({
accessKeyId: config.aws.accessKeyId,
secretAccessKey: config.aws.secretAccessKey,
region: config.aws.region,
apiVersion: '2010-12-01'
});
var uploadToS3 = async function(uploadParams) {
var response = await s3.upload(uploadParams).promise()
return response.Location
}

使用response.Location上传后,很容易获得文件的url。

现在我已经开始使用AWS SDK for S3 version 3来做同样的事情,但我并没有找到上传文件后获取url的方法。

// using AWS SDK version 3
const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");
var awsCredentials = {
region: config.aws.region,
credentials: { accessKeyId: config.aws.accessKeyId, secretAccessKey: config.aws.secretAccessKey }
}
var s3Client = new S3Client(awsCredentials)
var uploadToS3 = async function (uploadParams) {
const data = await s3Client.send(new PutObjectCommand(uploadParams))
if (data.$metadata.httpStatusCode == 200) {
let url = `https://${uploadParams.Bucket}.s3.ap-south-1.amazonaws.com/${uploadParams.Key}`
return url
}
}

在SDK版本3中,我不知道如何获取url,所以我需要手动构建,而不处理url的编码。

我找到了一些编码手动创建的url的方法,但这些方法是不可靠的
S3正在将带有空格和符号的URL编码为未知格式
Amazon S3 URL编码

我想应该有AWS SDK的方式来获取url,就像我在SDK版本2中获得的那样。

这里是我如何在Nestjs Framework中编码url的示例,您可以在代码中使用相同的javascript函数"encodeURIComponent":

...    
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { v4 as uuidv4 } from 'uuid';
...
private s3Client: S3Client;
constructor(
private readonly configService: ConfigService
) {
this.s3Client = new S3Client({
region: configService.get<string>('AWS_REGION'),
credentials:{
accessKeyId: configService.get<string>('AWS_ACCESS_KEY_ID'),
secretAccessKey: configService.get<string>('AWS_SECRET_ACCESS_KEY'),
}
});
}
...
async upload(dataBuffer: Buffer, originalname: string): Promise<FileUploadResponse> {
const fileName = `${uuidv4()}-${originalname}`;
const encodeFileName = encodeURIComponent(fileName);
const bucketName = this.configService.get<string>('AWS_BUCKET_NAME');
const command: PutObjectCommand = new PutObjectCommand({
Bucket: bucketName,
Key: fileName,
Body: dataBuffer
});
const uploadResult = await this.s3Client.send(command);
return `https://${bucketName}.s3.amazonaws.com/${encodeFileName}`;
}
...
}

相关内容

  • 没有找到相关文章

最新更新