شروع به کار با پارتیشن s3 RGW #

پیش نیازها #

پکیچ Nuget برای کتابخانه AWSSDK.S3 را از آدرس https://www.nuget.org/packages/AWSSDK.S3 دریافت کنید یا از کد زیر استفاده کنید:

dotnet new console --name <PROJECT_NAME>
cd <PROJECT_NAME>
dotnet add package AWSSDK.S3

و آن را اجر کنید:

dotnet run

لینک مستندات و گیتهاب #

برای دسترسی به مستندات کامل و جزییات بیشتر  به مستندات و گیت‌هاب این کتابخانه مراجعه کنید.

کانیفگ اطلاعات دسترسی در #C #

کلید دسترسی و کلید خصوصی (Access Key و Secret Key) و آدرس اندپوینت(ٍEndpoint) فضای ابری پشتیبان خود را مطابق کد زیر در تنظیمات وارد کنید:

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0

using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;

namespace CreateBucket
{
    public class CreateBucket
    {
        // This example shows how to use Amazon Simple Storage Service (Amazon S3)
        // to create a new Amazon S3 bucket. The examples uses AWS SDK for .NET 3.5 and
        // .NET 5.0.

        private static IAmazonS3 _s3Client;

        static async Task Main()
        {
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
            var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
            _s3Client = new AmazonS3Client(awsCredentials, config);

            // Continue your code here
        }
    }
}


نمونه کد بارگزاری آبجکت در فضای ابری پشتیبان #

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier:  Apache - 2.0

using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;
using System.Reflection;

namespace UploadObject
{
    // The following example shows two different methods for uploading data to
    // an Amazon Simple Storage Service (Amazon S3) bucket. The method,
    // UploadObjectFromFileAsync, uploads an existing file to an Amazon S3
    // bucket. The method, UploadObjectFromContentAsync, creates a new
    // file containing the text supplied to the method. The application
    // was created using AWS SDK for .NET 3.5 and .NET 5.0.

    class UploadObject
    {
        private static IAmazonS3 _s3Client;

        private const string BUCKET_NAME = "<BUCKET_NAME>";
        private const string OBJECT_NAME = "<OBJECT_NAME>";

        private static string LOCAL_PATH = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        static async Task Main()
        {
            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
            var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
            _s3Client = new AmazonS3Client(awsCredentials, config);

            // The method expects the full path, including the file name.
            var path = $"{LOCAL_PATH}/{OBJECT_NAME}";

            await UploadObjectFromFileAsync(_s3Client, BUCKET_NAME, OBJECT_NAME, path);
        }

        /// <summary>
        /// This method uploads a file to an Amazon S3 bucket. This
        /// example method also adds metadata for the uploaded file.
        /// </summary>
        /// <param name="client">An initialized Amazon S3 client object.</param>
        /// <param name="bucketName">The name of the S3 bucket to upload the
        /// file to.</param>
        /// <param name="objectName">The destination file name.</param>
        /// <param name="filePath">The full path, including file name, to the
        /// file to upload. This doesn't necessarily have to be the same as the
        /// name of the destination file.</param>
        private static async Task UploadObjectFromFileAsync(
            IAmazonS3 client,
            string bucketName,
            string objectName,
            string filePath)
        {
            try
            {
                var putRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = objectName,
                    FilePath = filePath,
                    ContentType = "text/plain"
                };

                putRequest.Metadata.Add("x-amz-meta-title", "someTitle");

                PutObjectResponse response = await client.PutObjectAsync(putRequest);

                foreach (PropertyInfo prop in response.GetType().GetProperties())
                {
                    Console.WriteLine($"{prop.Name}: {prop.GetValue(response, null)}");
                }

                Console.WriteLine($"Object {OBJECT_NAME} added to {bucketName} bucket");
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }
        }
    }
}


نمونه کد بارگذاری Multi-part آبجکت در فضای ابری پشتیبان #

برای فایل های با حجم بالا در فضای ابری بهتر است حالت multi part Upload فعال باشد. مانند نمونه زیر فایل خود را بارگزاری کنید:

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier:  Apache-2.0

namespace UploadFileMPULowLevelAPIExample
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.Runtime;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// Uses the Amazon Simploe Storage Service (Amazon S3) low-level API to
    /// upload an object from the local system to an Amazon S3 bucket. This
    /// example was created using the AWS SDK for .NET verion 3.7 and
    /// .NET Core 5.0.
    /// </summary>
    public class UploadFileMPULowLevelAPI
    {
        private static IAmazonS3 _s3Client;

        private const string BUCKET_NAME = "<BUCKET_NAME>";
        private static string LOCAL_PATH = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        private const string OBJECT_NAME = "<OBJECT_NAME>";

        public static async Task Main()
        {
            string bucketName = BUCKET_NAME;
            string keyName = OBJECT_NAME;
            string filePath = $"{LOCAL_PATH}/{keyName}";

            var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
            var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
            _s3Client = new AmazonS3Client(awsCredentials, config);

            Console.WriteLine("Uploading an object...");
            await UploadObjectAsync(_s3Client, bucketName, keyName, filePath);
        }

        /// <summary>
        /// Uses the low-level API to upload an object from the local system to
        /// to an S3 bucket.
        /// </summary>
        /// <param name="client">The initialized S3 client object used to
        /// perform the multi-part upload.</param>
        /// <param name="bucketName">>The name of the bucket to which to upload
        /// the file.</param>
        /// <param name="keyName">The file name to be used in the
        /// destination S3 bucket.</param>
        /// <param name="filePath">The path, including the file name of the
        /// file to be uploaded to the S3 bucket.</param>
        public static async Task UploadObjectAsync(
            IAmazonS3 client,
            string bucketName,
            string keyName,
            string filePath)
        {
            // Create list to store upload part responses.
            List<UploadPartResponse> uploadResponses = new ();

            // Setup information required to initiate the multipart upload.
            InitiateMultipartUploadRequest initiateRequest = new ()
            {
                BucketName = bucketName,
                Key = keyName,
            };

            // Initiate the upload.
            InitiateMultipartUploadResponse initResponse =
                await client.InitiateMultipartUploadAsync(initiateRequest);

            // Upload parts.
            long contentLength = new FileInfo(filePath).Length;
            long partSize = 400 * (long)Math.Pow(2, 20); // 400 MB

            try
            {
                Console.WriteLine("Uploading parts");

                long filePosition = 0;
                for (int i = 1; filePosition < contentLength; i++)
                {
                    UploadPartRequest uploadRequest = new ()
                    {
                        BucketName = bucketName,
                        Key = keyName,
                        UploadId = initResponse.UploadId,
                        PartNumber = i,
                        PartSize = partSize,
                        FilePosition = filePosition,
                        FilePath = filePath,
                    };

                    // Track upload progress.
                    uploadRequest.StreamTransferProgress +=
                        new EventHandler<StreamTransferProgressArgs>(UploadPartProgressEventCallback);

                    // Upload a part and add the response to our list.
                    uploadResponses.Add(await client.UploadPartAsync(uploadRequest));

                    filePosition += partSize;
                }

                // Setup to complete the upload.
                CompleteMultipartUploadRequest completeRequest = new ()
                {
                    BucketName = bucketName,
                    Key = keyName,
                    UploadId = initResponse.UploadId,
                };
                completeRequest.AddPartETags(uploadResponses);

                // Complete the upload.
                CompleteMultipartUploadResponse completeUploadResponse =
                    await client.CompleteMultipartUploadAsync(completeRequest);

                Console.WriteLine($"Object {keyName} added to {bucketName} bucket");
            }
            catch (Exception exception)
            {
                Console.WriteLine($"An AmazonS3Exception was thrown: {exception.Message}");

                // Abort the upload.
                AbortMultipartUploadRequest abortMPURequest = new ()
                {
                    BucketName = bucketName,
                    Key = keyName,
                    UploadId = initResponse.UploadId,
                };
                await client.AbortMultipartUploadAsync(abortMPURequest);
            }
        }

        /// <summary>
        /// Handles the UploadProgress even to display the progress of the
        /// S3 multi-part upload.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">The event parameters.</param>
        public static void UploadPartProgressEventCallback(object sender, StreamTransferProgressArgs e)
        {
            Console.WriteLine($"{e.TransferredBytes}/{e.TotalBytes}");
        }
    }
}


برای نمونه های بیشتر به آدرس https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3 بروید.