Amazon Simple Storage Service
开发人员指南 (API 版本 2006-03-01)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 Amazon AWS 入门

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

以下 C# 代码示例将使用两个 PutObjectRequest 请求创建两个对象:

  • 第一个 PutObjectRequest 请求将文本字符串保存为示例对象数据。它还指定存储桶和对象键名称。

  • 第二个 PutObjectRequest 请求通过指定文件名上传文件。此请求还指定 ContentType 标头和可选对象元数据 (标题)。

有关如何创建和测试有效示例的说明,请参阅 运行 Amazon S3 .NET 代码示例

using Amazon.S3; using Amazon.S3.Model; using System; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class UploadObjectTest { private const string bucketName = "*** bucket name ***"; // Example creates two objects (for simplicity, we upload same file twice). // You specify key names for these objects. private const string keyName1 = "*** key name for first object created ***"; private const string keyName2 = "*** key name for second object created ***"; private const string filePath = @"*** file path ***"; private static readonly RegionEndpoint bucketRegion = RegionEndpoint.EUWest1; private static IAmazonS3 client; public static void Main() { client = new AmazonS3Client(bucketRegion); WritingAnObjectAsync().Wait(); } static async Task WritingAnObjectAsync() { try { // 1. Put object-specify only key name for the new object. var putRequest1 = new PutObjectRequest { BucketName = bucketName, Key = keyName1, ContentBody = "sample text" }; PutObjectResponse response1 = await client.PutObjectAsync(putRequest1); // 2. Put the object-set ContentType and add metadata. var putRequest2 = new PutObjectRequest { BucketName = bucketName, Key = keyName2, FilePath = filePath, ContentType = "text/plain" }; putRequest2.Metadata.Add("x-amz-meta-title", "someTitle"); } catch (AmazonS3Exception e) { Console.WriteLine( "Error encountered ***. Message:'{0}' when writing an object" , e.Message); } catch (Exception e) { Console.WriteLine( "Unknown encountered on server. Message:'{0}' when writing an object" , e.Message); } } } }