upload files to amazon s3 using asp.net mvc

Amazon S3 is very fast growing cloud computing and storage hosting. I was working with amazon s3 cloud server to upload images using file upload with asp.net mvc. I have faced some problems due to version upgrade by amazon s3. I get the code older one that wasn’t compatible with new version and some function removed.

After spend some time to research I get the idea to implement the actual working code. Please find below the latest working code example. you just need to add Amazon s3 library using nuget and then get the Access Key & Secret Key.

Find below working code example
Set AWS AccessKey, SecretKey and BucketName like below:-

 private static readonly string _awsAccessKey = "AccessKey";
 private static readonly string _awsSecretKey = "SecretKey";
 private static readonly string _bucketName = "BucketName";

Code to deploy uploaded image to amazon cloud. It will create UPLOADS folder in your Bucket.

 foreach (string file in Request.Files)
                    var uploadedFile = Request.Files[file];
                    if (uploadedFile != null)
                        AmazonS3Config S3Config = new AmazonS3Config
                            RegionEndpoint = RegionEndpoint.USEast1, //its default region set by amazon

                        AmazonS3Client client;
                        using (client = new Amazon.S3.AmazonS3Client(_awsAccessKey, _awsSecretKey, S3Config))

                            var request = new PutObjectRequest()
                                BucketName = _bucketName,
                                CannedACL = S3CannedACL.PublicRead,//PERMISSION TO FILE PUBLIC ACCESIBLE
                                Key = string.Format("UPLOADS/{0}", uploadedFile.FileName),
                                InputStream = uploadedFile.InputStream//SEND THE FILE STREAM

                            var response = client.PutObject(request);
                            if (Convert.ToString(response.HttpStatusCode) == "OK")
                               //do what you want..

It’s very simple and easy code to achieve upload to amazon s3 server. If you still face any problem, then feel free to contact me.

Happy coding…

Posted by | View Post | View Group