Uploading a file aws s3 using high level api TransferUtility

In the previous article, we have seen the code for uploading a file to amazon aws s3 using low level api in asp.net. In this article I’ll illustrate you the same scenario using transfer utility that is Uploading a file amazon aws s3 using high level api with the help of transfer utility. To start up, make sure you have integrated the aws sdk for dot.net with the sample application where we perform this operation.

The file uploading process with high level api includes two steps, creating an instance for transfer utility and second, executing the transferutility.upload method overloads based on your requirement. The api gives the flexibility to set the timeout to avoid timeout issues while uploading large files. This can be achieved using TransferUtilityConfig.DefaultTimeout.

There are four methods to upload a file using transferutility instance. Firstly, when uploading file using file path and using file name as keyname

TransferUtility TransferUtilityObj = new TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.USEast1));

TransferUtilityObj.Upload(filePath, existingBucketName);

Secondly, mentioning the key name explicitly as below,

TransferUtilityObj.Upload(filePath,existingBucketName, keyName);

Thirdly, from a file stream,

using (FileStream fileToUpload = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    TransferUtilityObj.Upload(fileToUpload,
                                               existingBucketName, keyName);
                }

Fourth, using advanced options,

TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName = existingBucketName,
                    FilePath = filePath,
                    StorageClass = S3StorageClass.ReducedRedundancy,
                    PartSize = 6291456, // 6 MB.
                    Key = keyName,
                    CannedACL = S3CannedACL.PublicRead
                };
                fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
                fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
                TransferUtilityObj.Upload(fileTransferUtilityRequest);

The complete implementation code goes as follows. Here am using the fourth option to upload a file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Amazon.S3;
using Amazon.S3.Transfer;
using System.IO;
using Amazon.S3.Model;

/// <summary>
/// Summary description for awssdkcode
/// </summary>
namespace sampleapp
{
    public class awssdkcode
    {

        static string existingBucketName = "****BucketName*****";
        static string keyName = "****foldername******";
        //  static string filePath           = "*** Provide file name ***";
        public static string uploadfiletoamazon(string filepath, string filename)
        {

            try
            {

                string accessKey = "****accesskey*******";
                string secretKey = "*****Secretkey**********";
                                TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USEast1));


                // 4.Specify advanced settings/options.
                TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName = existingBucketName,
                    FilePath = filepath,
                    StorageClass = S3StorageClass.ReducedRedundancy,
                    PartSize = 6291456, // 6 MB.
                    Key = keyName + "/" + filename,

                    CannedACL = S3CannedACL.PublicRead
                };
                String ctype=getcontenttype(Path.GetExtension(FileName));

                fileTransferUtilityRequest.Metadata.Add("Content-Type", ctype);
                //   fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
                fileTransferUtility.Upload(fileTransferUtilityRequest);
                //Deleting Locally Saved File
                fileTransferUtility.Dispose();
                return "success";
            }
            catch (AmazonS3Exception s3Exception)
            {
                //  Console.WriteLine(s3Exception.Message,s3Exception.InnerException);
                throw new Exception(s3Exception.Message);
            }
        }
        private string GetContentType(string fileExtension)
        {
            string contentType = string.Empty;
            switch (fileExtension)
            {
                case "bmp": contentType = "image/bmp"; break;
                case "jpeg": contentType = "image/jpeg"; break;
                case "jpg": contentType = "image/jpg"; break;
                case "gif": contentType = "image/gif"; break;
                case "tiff": contentType = "image/tiff"; break;
                case "png": contentType = "image/png"; break;
                case "plain": contentType = "text/plain"; break;
                case "rtf": contentType = "text/rtf"; break;
                case "msword": contentType = "application/msword"; break;
                case "zip": contentType = "application/zip"; break;
                case "mpeg": contentType = "audio/mpeg"; break;
                case "pdf": contentType = "application/pdf"; break;
                case "xgzip": contentType = "application/x-gzip"; break;
                case "xcompressed": contentType = "application/x-compressed"; break;
            }
            return contentType;
        }

    }
}

Pass the filename and filepath to the above class file as below,

awssdkcode.uploadfiletoamazon(filepath,filename);

Thank you!!