AWS SDK .NET

使用 AWS 官方 SDK aws-sdk-net

注意: 由于七牛云存储上传对象 (Object) 请求中响应头 ETag 的算法与 AWS S3 服务不同,应用开发者需要忽略该异常。

  • 普通上传
using System;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.Runtime;

// 该示例为一个 Console Application
namespace UploadObjectApp
{
    class Program
    {
        private static string s3Endpoint = "https://api-s3.qiniu.com";
        private static string s3Region = "cn-east-1";
        private static string s3AccessKeyId = "<your-qiniu-access-key-id>";
        private static string s3AccessKeySecret = "<your-qiniu-access-key-secret>";
        private static string s3BucketName = "<your-qiniu-bucket>";
        private static string s3KeyName = "aws-sdk-net-3.1.40.0.zip";
        private static string filePath = "C:\\Users\\Administrator\\Downloads\\aws-sdk-net-3.1.40.0.zip";

        static void Main(string[] args)
        {
            AmazonS3Config s3Config = new AmazonS3Config
            {
                ServiceURL = s3Endpoint,
                AuthenticationRegion = s3Region,
                ForcePathStyle = true,
                SignatureVersion = "v4",
                SignatureMethod = Amazon.Runtime.SigningAlgorithm.HmacSHA256
            };

            var s3Client = new AmazonS3Client(s3AccessKeyId, s3AccessKeySecret, s3Config);

            putObject(client: s3Client);

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }

        static void putObject(AmazonS3Client client)
        {
            try
            {
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = s3BucketName,
                    Key = s3KeyName,
                    FilePath = filePath
                };

                PutObjectResponse response = client.PutObject(request);

                Console.WriteLine("Put Object => ETag: {0}", response.ETag);
            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine("Put Object => Code: {0}, Error: {1}", s3Exception.ErrorCode, s3Exception.Message);

                throw;
            }
            catch (AmazonClientException s3ClientException)
            {
                // 由于七牛云存储上传对象 (Object) 请求中响应头 *ETag* 的算法与 AWS S3 服务不同,应用开发者需要忽略该异常。
                if (s3ClientException.Message.Contains("Expected hash not equal to calculated hash"))
                {
                    Console.WriteLine("Ignore object hash checksum since algorithm of ETag in Qiniu Storage is different from AWS S3.");
                }
                else
                {
                    Console.WriteLine("Put Object => Error: {0}", s3ClientException.ToString());

                    throw;
                }
            }
        }
    }
}
  • 分块上传 I (Multipart Upload)
using System;
using System.Collections.Generic;
using System.IO;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.Runtime;

namespace S3ApiConsoleApplication
{
    class Program
    {
        private static string s3Endpoint = "https://api-s3.qiniu.com";
        private static string s3Region = "cn-east-1";
        private static string s3AccessKeyId = "<your-qiniu-access-key-id>";
        private static string s3AccessKeySecret = "<your-qiniu-access-key-secret>";
        private static string s3BucketName = "<your-qiniu-bucket>";
        private static string s3KeyName = "aws-sdk-net-3.1.40.0.zip";

        private static string filePath = "C:\\Users\\Administrator\\Downloads\\aws-sdk-net-3.1.40.0.zip";
        private static long filePartSize = 8 << 20; // 8M

        static void Main(string[] args)
        {
            AmazonS3Config s3Config = new AmazonS3Config
            {
                SignatureVersion = "v4",
                SignatureMethod = Amazon.Runtime.SigningAlgorithm.HmacSHA256,
                AuthenticationRegion = s3Region,
                ServiceURL = s3Endpoint,
                ForcePathStyle = true,
                BufferSize = (int)filePartSize
            };

            var s3Client = new AmazonS3Client(s3AccessKeyId, s3AccessKeySecret, s3Config);

            multipartUploadObject(client: s3Client, filePath: filePath, partSize: filePartSize);

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }

        static void multipartUploadObject(AmazonS3Client client, string filePath, long partSize)
        {
            // List to store uploaded part responses
            List<UploadPartResponse> parts = new List<UploadPartResponse>();

            // 1. initialize
            InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest
            {
                BucketName = s3BucketName,
                Key = s3KeyName
            };

            InitiateMultipartUploadResponse initResponse = client.InitiateMultipartUpload(initRequest);

            // 2. upload parts
            try
            {
                long fileSize = new FileInfo(filePath).Length;
                long filePos = 0;

                for (int i = 1; filePos < fileSize; i++)
                {
                    UploadPartRequest uploader = new UploadPartRequest
                    {
                        BucketName = s3BucketName,
                        Key = s3KeyName,
                        UploadId = initResponse.UploadId,
                        PartNumber = i,
                        PartSize = partSize,
                        FilePosition = filePos,
                        FilePath = filePath
                    };

                    UploadPartResponse part = client.UploadPart(uploader);

                    // record uploaded part
                    if (part != null)
                    {
                        Console.WriteLine("Multipart Upload Part: {0} - {1}", i, part.ETag);

                        parts.Add(item: part);
                    }

                    filePos += partSize;
                }

                // 3. complete
                CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
                {
                    BucketName = s3BucketName,
                    Key = s3KeyName,
                    UploadId = initResponse.UploadId
                };
                completeRequest.AddPartETags(parts);

                CompleteMultipartUploadResponse completeResponse = client.CompleteMultipartUpload(completeRequest);

                Console.WriteLine("Multipart Upload Complete: {0} - {1}", s3KeyName, completeResponse.Location);
            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine("Multipart Upload Object => Code: {0}, Error: {1}", s3Exception.ErrorCode, s3Exception.Message);

                throw;
            }
            catch (AmazonClientException s3ClientException)
            {
                // 由于七牛云存储上传对象 (Object) 请求中响应头 *ETag* 的算法与 AWS S3 服务不同,应用开发者需要忽略该异常。
                if (s3ClientException.Message.Contains("Expected hash not equal to calculated hash"))
                {
                    Console.WriteLine("Ignore object hash checksum since algorithm of ETag in Qiniu Storage is different from AWS S3.");
                }
                else
                {
                    Console.WriteLine("Multipart Upload Object => Error: {0}", s3ClientException.ToString());

                    throw;
                }
            }
        }
    }
}
  • 分块上传 II (Multipart Upload)
using System;
using Amazon.S3;
using Amazon.S3.Transfer;
using Amazon.Runtime;

namespace S3ApiConsoleApplication
{
    class Program
    {
        private static string s3Endpoint = "https://api-s3.qiniu.com";
        private static string s3Region = "cn-east-1";
        private static string s3AccessKeyId = "<your-qiniu-access-key-id>";
        private static string s3AccessKeySecret = "<your-qiniu-access-key-secret>";
        private static string s3BucketName = "<your-qiniu-bucket>";
        private static string s3KeyName = "aws-sdk-net-3.1.40.0.zip";

        private static string filePath = "C:\\Users\\Administrator\\Downloads\\aws-sdk-net-3.1.40.0.zip";
        private static long filePartSize = 8 << 20; // 8M

        static void Main(string[] args)
        {
            AmazonS3Config s3Config = new AmazonS3Config
            {
                SignatureVersion = "v4",
                SignatureMethod = Amazon.Runtime.SigningAlgorithm.HmacSHA256,
                AuthenticationRegion = s3Region,
                ServiceURL = s3Endpoint,
                ForcePathStyle = true,
                BufferSize = (int)filePartSize
            };

            var s3Client = new AmazonS3Client(s3AccessKeyId, s3AccessKeySecret, s3Config);

            transferUploadObject(client: s3Client, filePath: filePath, partSize: filePartSize);

            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }

        static void transferUploadObject(AmazonS3Client client, string filePath, long partSize)
        {
            try
            {
                TransferUtilityUploadRequest transferRequest = new TransferUtilityUploadRequest
                {
                    BucketName = s3BucketName,
                    Key = s3KeyName,
                    PartSize = partSize,
                    FilePath = filePath
                };

                TransferUtility transferUtility = new TransferUtility(client);
                transferUtility.Upload(transferRequest);

                Console.WriteLine("Transfer Upload: {0} - {1}", s3KeyName, transferUtility.ToString());
            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine("Multipart Upload Object => Code: {0}, Error: {1}", s3Exception.ErrorCode, s3Exception.Message);

                throw;
            }
            catch (AmazonClientException s3ClientException)
            {
                // 由于七牛云存储上传对象 (Object) 请求中响应头 *ETag* 的算法与 AWS S3 服务不同,应用开发者需要忽略该异常。
                if (s3ClientException.Message.Contains("Expected hash not equal to calculated hash"))
                {
                    Console.WriteLine("Ignore object hash checksum since algorithm of ETag in Qiniu Storage is different from AWS S3.");
                }
                else
                {
                    Console.WriteLine("Multipart Upload Object => Error: {0}", s3ClientException.ToString());

                    throw;
                }
            }
        }
    }
}

results matching ""

    No results matching ""