Amazon S3 示例将开发工具包用于 JavaScript V3 - AWS SDK for JavaScript

帮助我们改进AWS SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:AWS SDK for JavaScriptV3 API 参考指南详细描述了所有的 API 操作AWS SDK for JavaScript版本 3 (V3)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Amazon S3 示例将开发工具包用于 JavaScript V3

以下代码示例显示如何使用AWS SDK for JavaScriptVAmazon S3。

操作展示如何调用具体的 Amazon S3 函数的代码节选。

方案展示如何通过调用多个 Amazon S3 函数来完成特定任务的代码示例。

每个示例都包含一个指向以下内容的链接 GitHub其中包含了有关如何在上下文中设置和运行代码的说明。

操作

以下代码示例显示如何向 S3 存储桶添加跨源资源共享 (CORS) 规则。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

添加 CORS 规则。

// Import required AWS-SDK clients and commands for Node.js. import { PutBucketCorsCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Set parameters. // Create initial parameters JSON for putBucketCors. const thisConfig = { AllowedHeaders: ["Authorization"], AllowedMethods: [], AllowedOrigins: ["*"], ExposeHeaders: [], MaxAgeSeconds: 3000, }; // Assemble the list of allowed methods based on command line parameters const allowedMethods = []; process.argv.forEach(function (val, index, array) { if (val.toUpperCase() === "POST") { allowedMethods.push("POST"); } if (val.toUpperCase() === "GET") { allowedMethods.push("GET"); } if (val.toUpperCase() === "PUT") { allowedMethods.push("PUT"); } if (val.toUpperCase() === "PATCH") { allowedMethods.push("PATCH"); } if (val.toUpperCase() === "DELETE") { allowedMethods.push("DELETE"); } if (val.toUpperCase() === "HEAD") { allowedMethods.push("HEAD"); } }); // Copy the array of allowed methods into the config object thisConfig.AllowedMethods = allowedMethods; // Create an array of configs then add the config object to it. const corsRules = new Array(thisConfig); // Create CORS parameters. export const corsParams = { Bucket: "BUCKET_NAME", CORSConfiguration: { CORSRules: corsRules }, }; export async function run() { try { const data = await s3Client.send(new PutBucketCorsCommand(corsParams)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } } run();

以下代码示例显示如何添加策略到 S3 存储桶。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

添加策略。

// Import required AWS SDK clients and commands for Node.js. import { CreateBucketCommand, PutBucketPolicyCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. const BUCKET_NAME = "BUCKET_NAME"; export const bucketParams = { Bucket: BUCKET_NAME, }; // Create the policy in JSON for the S3 bucket. const readOnlyAnonUserPolicy = { Version: "2012-10-17", Statement: [ { Sid: "AddPerm", Effect: "Allow", Principal: "*", Action: ["s3:GetObject"], Resource: [""], }, ], }; // Create selected bucket resource string for bucket policy. const bucketResource = "arn:aws:s3:::" + BUCKET_NAME + "/*"; //BUCKET_NAME readOnlyAnonUserPolicy.Statement[0].Resource[0] = bucketResource; // Convert policy JSON into string and assign into parameters. const bucketPolicyParams = { Bucket: BUCKET_NAME, Policy: JSON.stringify(readOnlyAnonUserPolicy), }; export const run = async () => { try { const data = await s3Client.send( new CreateBucketCommand(bucketParams) ); console.log('Success, bucket created.', data) try { const response = await s3Client.send( new PutBucketPolicyCommand(bucketPolicyParams) ); console.log("Success, permissions added to bucket", response); } catch (err) { console.log("Error adding policy to S3 bucket.", err); } } catch (err) { console.log("Error creating S3 bucket.", err); } }; run();

以下代码示例显示如何将 S3 对象从一个存储桶复制到另一个存储桶。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

复制对象。

// Get service clients module and commands using ES6 syntax. import { CopyObjectCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Set the bucket parameters. export const params = { Bucket: "DESTINATION_BUCKET_NAME", CopySource: "/SOURCE_BUCKET_NAME/OBJECT_NAME", Key: "OBJECT_NAME" }; // Create the Amazon S3 bucket. export const run = async () => { try { const data = await s3Client.send(new CopyObjectCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
  • 有关详细信息,请参阅。CopyObjectAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何创建 S3 存储桶。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

创建存储桶。

// Get service clients module and commands using ES6 syntax. import { CreateBucketCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Set the bucket parameters. export const bucketParams = { Bucket: "BUCKET_NAME" }; // Create the Amazon S3 bucket. export const run = async () => { try { const data = await s3Client.send(new CreateBucketCommand(bucketParams)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何从 S3 存储桶中删除策略。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

删除存储桶策略。

// Import required AWS SDK clients and commands for Node.js. import { DeleteBucketPolicyCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Set the bucket parameters export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new DeleteBucketPolicyCommand(bucketParams)); console.log("Success", data + ", bucket policy deleted"); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; // Invoke run() so these examples run out of the box. run();

以下代码示例显示如何删除空的 S3 存储桶。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

删除存储桶。

// Import required AWS SDK clients and commands for Node.js. import { DeleteBucketCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Set the bucket parameters export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new DeleteBucketCommand(bucketParams)); return data; // For unit tests. console.log("Success - bucket deleted"); } catch (err) { console.log("Error", err); } }; // Invoke run() so these examples run out of the box. run();

以下代码示例显示如何删除 S3 对象。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

删除对象。

import { DeleteObjectCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js" // Helper function that creates an Amazon S3 service client module. export const bucketParams = { Bucket: "BUCKET_NAME", Key: "KEY" }; export const run = async () => { try { const data = await s3Client.send(new DeleteObjectCommand(bucketParams)); console.log("Success. Object deleted.", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
  • 有关详细信息,请参阅。DeleteObjectAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何从 S3 存储桶中删除多个对象。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

删除多个对象。

import { DeleteObjectsCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js" // Helper function that creates an Amazon S3 service client module. export const bucketParams = { Bucket: "BUCKET_NAME", Delete: { Objects: [ { Key: "KEY_1", }, { Key: "KEY_2", }, ], }, }; export const run = async () => { try { const data = await s3Client.send(new DeleteObjectsCommand(bucketParams)); return data; // For unit tests. console.log("Success. Object deleted."); } catch (err) { console.log("Error", err); } }; run();

删除存储桶中的所有对象。

import { ListObjectsCommand, DeleteObjectCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new ListObjectsCommand(bucketParams)); return data; // For unit tests. let i = 0; let noOfObjects = data.Contents; for (let i = 0; i < noOfObjects.length; i++) { const data = await s3Client.send( new DeleteObjectCommand({ Bucket: bucketParams.Bucket, Key: noOfObjects[i].Key, }) ); } console.log("Success. Objects deleted."); } catch (err) { console.log("Error", err); } }; run();
  • 有关详细信息,请参阅。DeleteObjectsAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何从 S3 存储桶中删除网站配置。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

从存储桶中删除网站配置。

// Import required AWS SDK clients and commands for Node.js. import { DeleteBucketWebsiteCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for calling export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new DeleteBucketWebsiteCommand(bucketParams)); return data; // For unit tests. console.log("Success", data); } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何获取 S3 存储桶的跨源资源共享 (CORS) 规则。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

获取存储桶的 CORS 策略。

// Import required AWS SDK clients and commands for Node.js. import { GetBucketCorsCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for calling export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new GetBucketCorsCommand(bucketParams)); console.log("Success", JSON.stringify(data.CORSRules)); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何从 S3 存储桶中的对象读取数据。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

下载对象。

// Import required AWS SDK clients and commands for Node.js. import { GetObjectCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. export const bucketParams = { Bucket: "BUCKET_NAME", Key: "KEY", }; export const run = async () => { try { // Create a helper function to convert a ReadableStream to a string. const streamToString = (stream) => new Promise((resolve, reject) => { const chunks = []; stream.on("data", (chunk) => chunks.push(chunk)); stream.on("error", reject); stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); }); // Get the object} from the Amazon S3 bucket. It is returned as a ReadableStream. const data = await s3Client.send(new GetObjectCommand(bucketParams)); return data; // For unit tests. // Convert the ReadableStream to a string. const bodyContents = await streamToString(data.Body); console.log(bodyContents); return bodyContents; } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何获取 S3 存储桶的访问控制列表 (ACL)。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

获取 ACL 权限。

// Import required AWS SDK clients and commands for Node.js. import { GetBucketAclCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters. export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new GetBucketAclCommand(bucketParams)); console.log("Success", data.Grants); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何获取 S3 存储桶的策略。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

获取存储桶策略。

// Import required AWS SDK clients and commands for Node.js. import { GetBucketPolicyCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for calling export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new GetBucketPolicyCommand(bucketParams)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何获取 S3 存储桶的网站配置。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

获取网站配置。

// Import required AWS SDK clients and commands for Node.js. import { GetBucketWebsiteCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for calling export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new GetBucketWebsiteCommand(bucketParams)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
  • 有关详细信息,请参阅。GetBucketWebsiteAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何列出 S3 存储桶。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

列出存储桶。

// Import required AWS SDK clients and commands for Node.js. import { ListBucketsCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. export const run = async () => { try { const data = await s3Client.send(new ListBucketsCommand({})); console.log("Success", data.Buckets); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何列出 S3 存储桶中的对象。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

列出对象。

// Import required AWS SDK clients and commands for Node.js. import { ListObjectsCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for the bucket export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new ListObjectsCommand(bucketParams)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

列出 1000 个或更多对象。

// Import required AWS SDK clients and commands for Node.js. import { ListObjectsCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for the bucket export const bucketParams = { Bucket: "BUCKET_NAME" }; export async function run() { // Declare truncated as a flag that the while loop is based on. let truncated = true; // Declare a variable to which the key of the last element is assigned to in the response. let pageMarker; // while loop that runs until 'response.truncated' is false. while (truncated) { try { const response = await s3Client.send(new ListObjectsCommand(bucketParams)); // return response; //For unit tests response.Contents.forEach((item) => { console.log(item.Key); }); // Log the key of every item in the response to standard output. truncated = response.IsTruncated; // If truncated is true, assign the key of the last element in the response to the pageMarker variable. if (truncated) { pageMarker = response.Contents.slice(-1)[0].Key; // Assign the pageMarker value to bucketParams so that the next iteration starts from the new pageMarker. bucketParams.Marker = pageMarker; } // At end of the list, response.truncated is false, and the function exits the while loop. } catch (err) { console.log("Error", err); truncated = false; } } } run();
  • 有关详细信息,请参阅。ListObjectsAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何为 S3 存储桶设置新的访问控制列表 (ACL)。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

放置存储桶 ACL。

// Import required AWS SDK clients and commands for Node.js. import { PutBucketAclCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Set the parameters. For more information, // see https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketAcl-property. export const bucketParams = { Bucket: "BUCKET_NAME", // 'GrantFullControl' allows grantee the read, write, read ACP, and write ACL permissions on the bucket. // Use a canonical user ID for an AWS account, formatted as follows: // id=002160194XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXa7a49125274 GrantFullControl: "GRANTEE_1", // 'GrantWrite' allows grantee to create, overwrite, and delete any object in the bucket. // For example, 'uri=http://acs.amazonaws.com/groups/s3/LogDelivery' GrantWrite: "GRANTEE_2", }; export const run = async () => { try { const data = await s3Client.send(new PutBucketAclCommand(bucketParams)); console.log("Success, permissions added to bucket", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何设置 S3 存储桶的网站配置。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

设置网站配置。

// Import required AWS SDK clients and commands for Node.js. import { PutBucketWebsiteCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Create the parameters for the bucket export const bucketParams = { Bucket: "BUCKET_NAME" }; export const staticHostParams = { Bucket: bucketParams, WebsiteConfiguration: { ErrorDocument: { Key: "", }, IndexDocument: { Suffix: "", }, }, }; export const run = async () => { // Insert specified bucket name and index and error documents into parameters JSON // from command line arguments staticHostParams.Bucket = bucketParams; staticHostParams.WebsiteConfiguration.IndexDocument.Suffix = "INDEX_PAGE"; // The index document inserted into parameters JSON. staticHostParams.WebsiteConfiguration.ErrorDocument.Key = "ERROR_PAGE"; // The error document inserted into parameters JSON. // Set the new website configuration on the selected bucket. try { const data = await s3Client.send(new PutBucketWebsiteCommand(staticHostParams)); console.log("Success", data); } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何将对象上传到 S3 存储桶。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

创建并上载对象。

// Import required AWS SDK clients and commands for Node.js. import { PutObjectCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Set the parameters. export const bucketParams = { Bucket: "BUCKET_NAME", // Specify the name of the new object. For example, 'index.html'. // To create a directory for the object, use '/'. For example, 'myApp/package.json'. Key: "OBJECT_NAME", // Content of the new object. Body: "BODY", }; // Create and upload the object to the S3 bucket. export const run = async () => { try { const data = await s3Client.send(new PutObjectCommand(bucketParams)); return data; // For unit tests. console.log( "Successfully uploaded object: " + bucketParams.Bucket + "/" + bucketParams.Key ); } catch (err) { console.log("Error", err); } }; run();

上载对象。

// Import required AWS SDK clients and commands for Node.js. import { PutObjectCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. import {path} from "path"; import {fs} from "fs"; const file = "OBJECT_PATH_AND_NAME"; // Path to and name of object. For example '../myFiles/index.js'. const fileStream = fs.createReadStream(file); // Set the parameters export const uploadParams = { Bucket: "BUCKET_NAME", // Add the required 'Key' parameter using the 'path' module. Key: path.basename(file), // Add the required 'Body' parameter Body: fileStream, }; // Upload file to specified bucket. export const run = async () => { try { const data = await s3Client.send(new PutObjectCommand(uploadParams)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();

场景

以下代码示例显示如何为 S3 创建预签名 URL 以及如何上传对象。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

创建预签名 URL 以将对象上传到存储桶。

// Import the required AWS SDK clients and commands for Node.js import { CreateBucketCommand, DeleteObjectCommand, PutObjectCommand, DeleteBucketCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; import fetch from "node-fetch"; // Set parameters // Create a random name for the Amazon Simple Storage Service (Amazon S3) bucket and key export const bucketParams = { Bucket: `test-bucket-${Math.ceil(Math.random() * 10 ** 10)}`, Key: `test-object-${Math.ceil(Math.random() * 10 ** 10)}`, Body: "BODY" }; export const run = async () => { try { // Create an S3 bucket. console.log(`Creating bucket ${bucketParams.Bucket}`); await s3Client.send(new CreateBucketCommand({ Bucket: bucketParams.Bucket })); console.log(`Waiting for "${bucketParams.Bucket}" bucket creation...`); } catch (err) { console.log("Error creating bucket", err); } try { // Create a command to put the object in the S3 bucket. const command = new PutObjectCommand(bucketParams); // Create the presigned URL. const signedUrl = await getSignedUrl(s3Client, command, { expiresIn: 3600, }); console.log( `\nPutting "${bucketParams.Key}" using signedUrl with body "${bucketParams.Body}" in v3` ); console.log(signedUrl); const response = await fetch(signedUrl, {method: 'PUT', body: bucketParams.Body}); console.log( `\nResponse returned by signed URL: ${await response.text()}\n` ); } catch (err) { console.log("Error creating presigned URL", err); } try { // Delete the object. console.log(`\nDeleting object "${bucketParams.Key}"} from bucket`); await s3Client.send( new DeleteObjectCommand({ Bucket: bucketParams.Bucket, Key: bucketParams.Key }) ); } catch (err) { console.log("Error deleting object", err); } try { // Delete the S3 bucket. console.log(`\nDeleting bucket ${bucketParams.Bucket}`); await s3Client.send( new DeleteBucketCommand({ Bucket: bucketParams.Bucket }) ); } catch (err) { console.log("Error deleting bucket", err); } }; run();

创建预签名 URL 以从存储桶下载对象。

// Import the required AWS SDK clients and commands for Node.js import { CreateBucketCommand, PutObjectCommand, GetObjectCommand, DeleteObjectCommand, DeleteBucketCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; const fetch = require("node-fetch"); // Set parameters // Create a random names for the S3 bucket and key. export const bucketParams = { Bucket: `test-bucket-${Math.ceil(Math.random() * 10 ** 10)}`, Key: `test-object-${Math.ceil(Math.random() * 10 ** 10)}`, Body: "BODY" }; export const run = async () => { // Create an S3 bucket. try { console.log(`Creating bucket ${bucketParams.Bucket}`); const data = await s3Client.send( new CreateBucketCommand({ Bucket: bucketParams.Bucket }) ); return data; // For unit tests. console.log(`Waiting for "${bucketParams.Bucket}" bucket creation...\n`); } catch (err) { console.log("Error creating bucket", err); } // Put the object in the S3 bucket. try { console.log(`Putting object "${bucketParams.Key}" in bucket`); const data = await s3Client.send( new PutObjectCommand({ Bucket: bucketParams.Bucket, Key: bucketParams.Key, Body: bucketParams.Body, }) ); return data; // For unit tests. } catch (err) { console.log("Error putting object", err); } // Create a presigned URL. try { // Create the command. const command = new GetObjectCommand(bucketParams); // Create the presigned URL. const signedUrl = await getSignedUrl(s3Client, command, { expiresIn: 3600, }); console.log( `\nGetting "${bucketParams.Key}" using signedUrl with body "${bucketParams.Body}" in v3` ); console.log(signedUrl); const response = await fetch(signedUrl); console.log( `\nResponse returned by signed URL: ${await response.text()}\n` ); } catch (err) { console.log("Error creating presigned URL", err); } // Delete the object. try { console.log(`\nDeleting object "${bucketParams.Key}"} from bucket`); const data = await s3Client.send( new DeleteObjectCommand({ Bucket: bucketParams.Bucket, Key: bucketParams.Key }) ); return data; // For unit tests. } catch (err) { console.log("Error deleting object", err); } // Delete the S3 bucket. try { console.log(`\nDeleting bucket ${bucketParams.Bucket}`); const data = await s3Client.send( new DeleteBucketCommand({ Bucket: bucketParams.Bucket, Key: bucketParams.Key }) ); return data; // For unit tests. } catch (err) { console.log("Error deleting object", err); } }; run();

以下代码示例显示了如何:

  • 创建存储桶。

  • 将文件上传到存储桶。

  • 从存储桶下载对象。

  • 将对象复制到存储桶中的子文件夹。

  • 列出存储桶中的对象。

  • 删除存储桶中的对象。

  • 删除存储桶。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

import { CreateBucketCommand, PutObjectCommand, CopyObjectCommand, DeleteObjectCommand, DeleteBucketCommand, GetObjectCommand } from "@aws-sdk/client-s3"; import { s3Client, REGION } from "../libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. if (process.argv.length < 5) { console.log( "Usage: node s3_basics.js <the bucket name> <the AWS Region to use> <object name> <object content>\n" + "Example: node s3_basics_full.js test-bucket 'test.txt' 'Test Content'" ); } const bucket_name = process.argv[2]; const object_key = process.argv[3]; const object_content = process.argv[4]; export const run = async (bucket_name, object_key, object_content) => { try { const create_bucket_params = { Bucket: bucket_name }; console.log("\nCreating the bucket, named " + bucket_name + "...\n"); console.log("about to create"); const data = await s3Client.send( new CreateBucketCommand(create_bucket_params) ); console.log("Bucket created at ", data.Location); try { console.log( "\nCreated and uploaded an object named " + object_key + " to first bucket " + bucket_name + " ...\n" ); // Set the parameters for the object to upload. const object_upload_params = { Bucket: bucket_name, // Specify the name of the new object. For example, 'test.html'. // To create a directory for the object, use '/'. For example, 'myApp/package.json'. Key: object_key, // Content of the new object. Body: object_content, }; // Create and upload the object to the first S3 bucket. await s3Client.send(new PutObjectCommand(object_upload_params)); console.log( "Successfully uploaded object: " + object_upload_params.Bucket + "/" + object_upload_params.Key ); try { const download_bucket_params = { Bucket: bucket_name, Key: object_key }; console.log( "\nDownloading " + object_key + " from" + bucket_name + " ...\n" ); // Create a helper function to convert a ReadableStream into a string. const streamToString = (stream) => new Promise((resolve, reject) => { const chunks = []; stream.on("data", (chunk) => chunks.push(chunk)); stream.on("error", reject); stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); }); // Get the object from the Amazon S3 bucket. It is returned as a ReadableStream. const data = await s3Client.send(new GetObjectCommand(download_bucket_params)); // Convert the ReadableStream to a string. const bodyContents = await streamToString(data.Body); console.log(bodyContents); try { // Copy the object from the first bucket to the second bucket. const copy_object_params = { Bucket: bucket_name, CopySource: "/" + bucket_name + "/" + object_key, Key: "copy-destination/" + object_key, }; console.log( "\nCopying " + object_key + " from" + bucket_name + " to " + bucket_name + "/" + copy_object_params.Key + " ...\n" ); await s3Client.send(new CopyObjectCommand(copy_object_params)); console.log("Success, object copied to folder."); try { console.log("\nDeleting " + object_key + " from" + bucket_name); const delete_object_from_bucket_params = { Bucket: bucket_name, Key: object_key, }; await s3Client.send( new DeleteObjectCommand(delete_object_from_bucket_params) ); console.log("Success. Object deleted from bucket."); try { console.log( "\nDeleting " + object_key + " from " + bucket_name + "/copy-destination folder" ); const delete_object_from_folder_params = { Bucket: bucket_name, Key: "copy-destination/" + object_key, }; await s3Client.send( new DeleteObjectCommand(delete_object_from_folder_params) ); console.log("Success. Object deleted from folder."); try { console.log( "\nDeleting the bucket named " + bucket_name + "...\n" ); const delete_bucket_params = {Bucket: bucket_name}; await s3Client.send( new DeleteBucketCommand(delete_bucket_params) ); console.log("Success. First bucket deleted."); return "Run successfully"; // For unit tests. } catch (err) { console.log("Error deleting object from folder.", err); process.exit(1); } } catch (err) { console.log("Error deleting bucket.", err); process.exit(1); } } catch (err) { console.log("Error deleting object from bucket.", err); process.exit(1); } } catch (err) { console.log("Error copying object from to folder", err); process.exit(1); } } catch (err) { console.log("Error downloading object", err); process.exit(1); } }catch (err) { console.log("Error creating and upload object to bucket", err); process.exit(1); } console.log("works"); } catch (err) { console.log("Error creating bucket", err); } }; run(bucket_name, object_key, object_content);