在 AWS JavaScript SDK v3 中,可以使用 S3Client 的 'putObject” 方法来完成 S3 ManagedUpload 相关的操作。
以下是示例代码:
const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");
const fs = require('fs');
async function uploadFileToS3() {
// Create S3 Client object
const s3 = new S3Client({ region: "us-west-2" });
// Set S3 bucket name and key
const bucketName = "myBucket";
const keyName = "myFile.txt";
// Read file content
const fileContent = fs.readFileSync("path/to/file.txt");
// Create PutObjectCommand with file content and required parameters
const command = new PutObjectCommand({
Bucket: bucketName,
Key: keyName,
Body: fileContent,
});
try {
// Execute PutObjectCommand to upload file to S3
const response = await s3.send(command);
console.log("File uploaded successfully! Object URL: " + response.Location);
} catch (err) {
console.log("Error uploading file:", err);
}
}
uploadFileToS3();
注意,此示例代码仅上传文件,但适用于任何 S3 ManagedUpload 操作。如果要使用其他选项(例如,设置 ACL、Content-Type 等),可以在 PutObjectCommand 中添加相应的属性。请参阅 AWS JavaScript SDK v3 的文档以获取更多信息。