当前位置: 首页 > 工具软件 > S3Uploader > 使用案例 >

C# 上传文件至S3

阳念
2023-12-01
using Amazon.S3;
using Amazon.S3.Encryption;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UploadToS3.Utility
{
    public class AmazonS3Uploader
    {
        private static string accessKey = ConfigurationManager.AppSettings["accessKey"];
        private static string secretKey = ConfigurationManager.AppSettings["secretKey"];
        private static string region = ConfigurationManager.AppSettings["region"];
        private static string bucketName = ConfigurationManager.AppSettings["bucketName"];
        private static string directory = ConfigurationManager.AppSettings["directory"];
        private static string kmskeyid = ConfigurationManager.AppSettings["kmskeyid"];

        AmazonS3Config config = new AmazonS3Config()
        {
            //ServiceURL = "https://s3.amazonaws.com",
            ServiceURL = "https://folder.s3.amazonaws.com/",
            RegionEndpoint = Amazon.RegionEndpoint.CNNorth1
        };
        /// <summary>
        /// 
        /// </summary>
        /// <param name="localFilePath"></param>
        /// <param name="fileNameInS3"></param>
        /// <returns></returns>
        public bool UploadFileToS3(string localFilePath, string fileNameInS3)
        {
            try
            {
                using (var client = new AmazonS3Client(accessKey, secretKey, config))
                {
                    PutObjectResponse response;
                    PutObjectRequest putObject = new PutObjectRequest
                    {
                        BucketName = bucketName + @"/" + directory,
                        Key = fileNameInS3,// object name and path
                        FilePath = localFilePath,// The full path and name to a file to be uploaded
                        ServerSideEncryptionKeyManagementServiceKeyId = kmskeyid,
                        ServerSideEncryptionMethod = ServerSideEncryptionMethod.AWSKMS,
                    };
                    response = client.PutObjectAsync(putObject).GetAwaiter().GetResult();
                    Console.WriteLine(response.HttpStatusCode);
                    LoggerHelper.Info("成功上传文件:" + fileNameInS3);
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Error($"{fileNameInS3}上传S3失败");
                throw ex;
            }
            return true; //indicate that the file was sent
        }
        
    }
}

 类似资料: