Created
October 18, 2016 05:21
-
-
Save hgirish/845546db39479dfaee2edf6d5840173f to your computer and use it in GitHub Desktop.
Code to Upload file using AmazonS3Client TransferUtility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.IO; | |
| using System.Threading.Tasks; | |
| using Amazon.S3; | |
| using Amazon.S3.Model; | |
| using Amazon.S3.Transfer; | |
| namespace AWSDemo.Models | |
| { | |
| public class S3Uploader | |
| { | |
| private readonly string _bucketName; | |
| private readonly TransferUtility _transferUtility; | |
| readonly log4net.ILog _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
| public S3Uploader(string bucketName, string awsAccessKeyId, string awsSecretAccessKey) | |
| { | |
| _bucketName = bucketName; | |
| AmazonS3Config s3Config = new AmazonS3Config(); | |
| // Very Important: Without this, code gives error: Amazon.S3.AmazonS3Exception: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint. | |
| s3Config.ServiceURL = "http://s3-external-1.amazonaws.com"; // S3 is independent of Region, so set default service url | |
| AmazonS3Client client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, s3Config); | |
| _transferUtility = new TransferUtility(client); | |
| } | |
| public async Task UploadFile(string filePath, string toPath) | |
| { | |
| filePath = filePath.ToLower(); | |
| toPath = toPath.ToLower(); | |
| TransferUtilityUploadRequest request = new TransferUtilityUploadRequest() | |
| { | |
| BucketName = _bucketName, | |
| FilePath = filePath, | |
| Key = toPath | |
| }; | |
| request.UploadProgressEvent += Request_UploadProgressEvent; | |
| await _transferUtility.UploadAsync(request); | |
| } | |
| private void Request_UploadProgressEvent(object sender, UploadProgressArgs e) | |
| { | |
| _logger.Debug($"Total Bytes: {e.TotalBytes}\t TransferredBytes: {e.TransferredBytes}\t FilePath {e.FilePath}\t {e.PercentDone}%"); | |
| } | |
| public void UploadFile(string filePath, Stream inputStream, double contentLength, string contentType) | |
| { | |
| try | |
| { | |
| var request = new PutObjectRequest | |
| { | |
| BucketName = _bucketName, | |
| InputStream = inputStream, | |
| ContentType = contentType, | |
| CannedACL = S3CannedACL.PublicRead, | |
| Key = filePath | |
| }; | |
| var ar = _transferUtility.S3Client.PutObject((request)); | |
| _logger.Debug(ar.ResponseMetadata); | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.Error(ex.Message, ex); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment