asp.net core series 69 Amazon S3 resource file upload example

Original: ASP.NET Core Series 69 Amazon S3 resource file upload example

A. Upload example

  Amazon Simple Storage Service is an Internet storage solutions. The service aims to reduce developers to scale the difficulty level network computing.

  Amazon S3 provides a simple Web service interface may be used at any time anywhere in the store on the Web and retrieve any amount of data. This service allows all developers can access the same data storage infrastructure with high scalability, reliability, security and fast inexpensive, Amazon use it to run its global network of websites. This service is aimed at bringing to maximize economies of scale for developers.

  Install-Package AWSSDK.S3 -Version 3.3.104.10

the using Amazon;
 the using Amazon.Runtime;
 the using Amazon.S3;
 the using Amazon.S3.Model;
 the using the System;
 the using the System.Collections.Generic;
 the using the System.IO;
 the using the System.Text;
 the using System.Threading.Tasks; 

/ * 
     / / upload basketball profile picture 
     AwsS3Helper S3 = new new AwsS3Helper (ResourceType.basketballnewsImg); 
     s3.WritingAnObjectAsync ( "E: \\ \\ test1.jpg 11") the Wait ();.     
 * / 
namespace AwsS3WithNetCore 
{ 

    ///  <the Summary> 
    / // Amazon S3 upload data (photos, videos, documents, etc.) 
     ///  </ the Summary>
    public  class AwsS3Helper 
    { 

        ///  <Summary> 
        /// area is Asia Hong
         ///  </ Summary> 
        Readonly RegionEndpoint bucketRegion = RegionEndpoint.GetBySystemName ( " AP--East. 1 " ); 


        ///  <Summary> 
        /// To Amazon S3 upload data (photos, videos, documents, etc.),
         /// you must first create S3 bucket in one AWS region, such as: the Asia-Pacific Hong Kong address, create a gfbk barrel
         /// then you any number of objects can be uploaded to the bucket.
        /// create an account for each AWS up to 100 buckets, a bucket can store any number of objects.
        /// Information: https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/dev/UsingBucket.html 
        ///  </ the Summary>
        Readonly  String bucketName = Constants.bucketName; 


        ///  <Summary> 
        /// request credentials S3
         ///  </ Summary> 
        Readonly AWSCredentials AWSCredentials = new new BasicAWSCredentials (Constants.accessKey, Constants.secretKey); 


        ///  <Summary> 
        /// requesting client
         ///  </ Summary> 
        AmazonS3Client client = null ; 


        ///  <Summary> 
        /// Upload resource type
         ///  </ Summary> 
        the resourceType _resourceType; 

        public AwsS3Helper (the resourceType resourceType) 
        {
            _resourceType = resourceType;
            client = new AmazonS3Client(awsCredentials, bucketRegion);
        }


        /// <summary>
        ///创建一个桶
        /// </summary>
        /// <returns></returns>
        public async Task CreateBucket()
        {
            var putBucketRequest = new PutBucketRequest
            {
                BucketName = bucketName,
                UseClientRegion = true
            };
            PutBucketResponse putBucketResponse = await client.PutBucketAsync(putBucketRequest);
            string bucketLocation = await FindBucketLocationAsync(client);
        }


        /// <summary>
        /// 查找桶所在的地区
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        private async Task<string> FindBucketLocationAsync(IAmazonS3 client)
        {
            string bucketLocation;
            var request = new GetBucketLocationRequest()
            {
                BucketName = bucketName
            };
            GetBucketLocationResponse response = await client.GetBucketLocationAsync(request);
            bucketLocation = response.Location.ToString();
            return bucketLocation;
        }



        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="uploadFilePath">上传的文件地址如:E:\test.jpg</param>
        /// <returns></returns>
        public async Task<bool> WritingAnObjectAsync(string uploadFilePath)
        {
            the try 
            { 
                String filename = uploadFilePath.Substring (uploadFilePath.LastIndexOf ( ' \\ ' ) + . 1 );
                 String Key = String .Format ( " Resource / IMG / {0} / {}. 1 " ., _resourceType.ToString () the Replace ( " the Img " , "" ), filename);
                 var putRequest2 = new new PutObjectRequest 
                { 
                    bucketname = bucketName,
                     // get and set key property. This key is used to identify the object in S3, s3 upload path + file name,
                    // not the S3 folder you can create a reference HTTPS: // www.cnblogs.com/web424/p/6840207.html 
                    Key = Key,
                     // owner gain complete control over an anonymous body is granted read access. If
                     // this policy for the object, which can be read from the browser, without having to verify 
                    CannedACL = S3CannedACL.PublicRead,
                     // upload the file path 
                    FilePath = uploadFilePath,
                     // marked object settings. Tag sets must be encoded as URL query parameters 
                    TagSet = new new List <the Tag> {
                                     new new the Tag {Key = " the Test " , the Value = "S3Test"} }
                    //ContentType = "image/png"
                };
                putRequest2.Metadata.Add("x-amz-meta-title", "AwsS3Net");
                PutObjectResponse response2 = await client.PutObjectAsync(putRequest2);
                return true;
            }
            catch (AmazonS3Exception e)
            {
                throw new Exception(string.Format("Error encountered ***. Message:'{0}' when writing an object", e.Message));
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Unknown encountered on server. Message:'{0}' when writing an object", e.Message));
            }
        }



        /// <summary>
        /// 上传文件 (未经测试)
        /// </summary>
        /// <param name="inputStream">以流的形式</param>
        /// <returns></returns>
        public async Task<bool> WritingAnObjectByStreamAsync(Stream inputStream,string filename)
        {
             
                };String Key = String .Format ( " Resource / IMG / {0} / {}. 1 " , _resourceType.ToString () the Replace (. " the Img " , "" ), filename);
             the try 
            { 
                var putRequest1 = new new PutObjectRequest 
                { 
                    bucketname = bucketName,
                     // create the object, specify the name of the key that uniquely identifies the object in the bucket 
                    key = key, 
                    InputStream = inputStream 
                PutObjectResponse response1 = the await client.PutObjectAsync(putRequest1);
                return true;
            }
            catch (AmazonS3Exception e)
            {
                throw new Exception(string.Format("Error encountered ***. Message:'{0}' when writing an object", e.Message));
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Unknown encountered on server. Message:'{0}' when writing an object", E.Message)); 
            } 
        } 


        ///  <Summary> 
        /// Removes an object
         ///  </ Summary> 
        ///  <param name = "Key"> deleted objects such as keys: resource / img / basketballnews / test1.jpg </ param> 
        ///  <Returns> </ Returns> 
        public  the async the Task < BOOL > DeleteAnObjectAsync ( String Key) 
        { 
            the try 
            { 
                // 1. Key only the Delete Object-name for the Specify The Object.
                var deleteRequest1 = new DeleteObjectRequest
                {
                    BucketName = bucketName,
                    Key = key
                };
                DeleteObjectResponse response1 = await client.DeleteObjectAsync(deleteRequest1);
                return true;
            }
            catch (AmazonS3Exception e)
            {
                throw new Exception(string.Format("Error encountered ***. Message:'{0}' when writing an object", e.Message));
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("ON the Message Server encountered Unknown:. '{0}' AN When Writing Object " , e.Message)); 
            } 
        } 


        ///  <Summary> 
        /// Get
         ///  </ Summary> 
        ///  <param name = "prefix"> limit to begin with a specified prefix response key </ param> 
        ///  <Returns> </ Returns> 
        public  the async the Task <List <S3Object >> ListObjectsAsync ( String prefix = "")
        {
            try
            {

                var list = new ListObjectsRequest
                {
                    BucketName = bucketName,
                    Prefix = prefix
                };

                ListObjectsResponse response1 = await client.ListObjectsAsync(list);

                return response1.S3Objects;
            }
            catch (AmazonS3Exception e)
            {
                throw new Exception(string.Format("Error encountered ***. Message:'{0}' when writing an object", e.Message));
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Unknown encountered on server. Message:'{0}' when writing an object", e.Message));
            }
        }
    }



    public enum ResourceType
    {
        basketballnewsImg,
        footballnewsImg,
        bannerImg,
        videoImg,
        logoImg
    }

    internal class Constants
    {
        internal const string bucketName = "gfbk";//Write your bucket name
        internal const string accessKey = "xxxxxx"; // write your IAM credentials first access key
        internal const string secretKey = "xxxxxx"; // write your IAM credentials second access key(secret key)
    }
}

 

   As follows:

 

  references: 

    https://aws.amazon.com/cn/developer/language/net/code-samples/net-code-samples/
    https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/dev/UploadObjSingleOpNET.html

 

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11324336.html