Amazon Simple Storage Service
开发人员指南 (API Version 2006-03-01)
AWS 服务或AWS文档中描述的功能,可能因地区/位置而异。点 击 Getting Started with Amazon AWS to see specific differences applicable to the China (Beijing) Region.

使用 适用于 .NET 的 AWS 开发工具包 上传对象

以下过程中的任务引导您使用 .NET 类来上传对象。API 提供了 PutObject 方法的多个变体 (重载),使您可以轻松地上传数据。

上传对象

1

创建 AmazonS3 类的实例。

2

执行 AmazonS3.PutObject 之一。您需要提供诸如存储桶名称、文件路径或流等信息。您可以通过创建 PutObjectRequest 类的实例提供此信息。

以下 C# 代码示例演示了上述任务。

Copy
static IAmazonS3 client; client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1); PutObjectRequest request = new PutObjectRequest() { BucketName = bucketName, Key = keyName, FilePath = filePath }; PutObjectResponse response2 = client.PutObject(request);

以下 C# 代码示例将上传对象。对象数据在代码中将提供为文字字符串。该示例将上传对象两次。

  • 第一个 PutObjectRequest 仅指定存储桶名称、键名称以及作为示例对象数据嵌入在代码中的文本字符串。

  • 第二个 PutObjectRequest 提供其他信息,包括可选对象元数据和 ContentType 标头。reqest 指定要上传的文件名。

每个对 AmazonS3.PutObject 的后续调用都将替换先前的上传。有关如何创建和测试有效示例的说明,请参阅 运行 Amazon S3 .NET 代码示例

Copy
using System; using Amazon.S3; using Amazon.S3.Model; namespace s3.amazon.com.docsamples { class UploadObject { static string bucketName = "*** bucket name ***"; static string keyName = "*** key name when object is created ***"; static string filePath = "*** absolute path to a sample file to upload ***"; static IAmazonS3 client; public static void Main(string[] args) { using (client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1)) { Console.WriteLine("Uploading an object"); WritingAnObject(); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } static void WritingAnObject() { try { PutObjectRequest putRequest1 = new PutObjectRequest { BucketName = bucketName, Key = keyName, ContentBody = "sample text" }; PutObjectResponse response1 = client.PutObject(putRequest1); // 2. Put object-set ContentType and add metadata. PutObjectRequest putRequest2 = new PutObjectRequest { BucketName = bucketName, Key = keyName, FilePath = filePath, ContentType = "text/plain" }; putRequest2.Metadata.Add("x-amz-meta-title", "someTitle"); PutObjectResponse response2 = client.PutObject(putRequest2); } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { Console.WriteLine("Check the provided AWS Credentials."); Console.WriteLine( "For service sign up go to http://aws.amazon.com/s3"); } else { Console.WriteLine( "Error occurred. Message:'{0}' when writing an object" , amazonS3Exception.Message); } } } } }