Uploading File To AWS S3 Using ASP.NET

In this article, I will show you how to upload a file (image/video/..) to Amazon S3 Bucket through an ASP.NET web application. For this, first you need to have an AWS account in Amazon Web Services. You can create AWS free tier account that's valid for 12 months. Visit this link to know more about a free tier account.

After signing into the AWS account, the next thing you need is to create security credentials for your account which will create a secret access key Id and secret access key. Below images show how to do this.

Account name> My Security Credentials.

ASP.NET

Continue to Security Credentials.

ASP.NET

Click (+) Acess Keys> create New Access Key button > download the key file or take note of your id and key somewhere.

ASP.NET

Next, create an S3 Bucket. Click "Services" tab and select S3 under Storage division. This will take you to Amazon S3 page. On clicking the "Create" button, the following pop up will come up. Give a bucket name and select a region. Click "Next" and allow the public to read it.

ASP.NET

Now, we need to create a bucket policy which allows us to create rules for managing access to our buckets and files.

Select your bucket > Permission tab > Bucket Policy > Policy Generator.

ASP.NET

This will take you to new page. Fill in the details as per your requirement. I have selected two actions - putobject and getobject. And in ARN, gie your bucket name such as  ‘test73’.

ASP.NET

Clicking "Add Statement" will enable a new button ‘Policy Generator’. Click that button, copy and paste the generated policy back in your bucket policy.

ASP.NET

Click "Save". Now, you are done with all Amazon settings. The next step is to create an ASP.NET Application.

Open Visual Studio, and go to File > New > website > ASP.NET Empty web Site. Give a project name and click OK.

ASP.NET

Add a new webform (empty) to your project. Now, we need to add two references - AWSSDK.Core and AWSSDK.S3 to our project. Open NuGet Package Manager in VS and search awssdk.

Download these two references to your project.

ASP.NET

Now, add a fileupload control and a button control to your webform. The code for the webform is shown below.

  1. using System;  
  2.   
  3. using System.IO;  
  4.   
  5. namespace awsTestUpload  
  6. {  
  7.     public partial class WebForm1 : System.Web.UI.Page  
  8.     {  
  9.         protected void Page_Load(object sender, EventArgs e)  
  10.         {  
  11.   
  12.         }  
  13.   
  14.         protected void upload(string path,string file)  
  15.         {  
  16.         }  
  17.   
  18.         protected void Button2_Click(object sender, EventArgs e)  
  19.         {  
  20.               
  21.          Stream st = FileUpload1.PostedFile.InputStream;  
  22.               
  23.             string name = Path.GetFileName(FileUpload1.FileName);  
  24.             string myBucketName = "test73"//your s3 bucket name goes here  
  25.             string s3DirectoryName = "";  
  26.             string s3FileName = @name;  
  27.             bool a;  
  28.             AmazonUploader myUploader = new AmazonUploader();  
  29.             a = myUploader.sendMyFileToS3(st, myBucketName, s3DirectoryName, s3FileName);  
  30.             if (a == true)  
  31.             {  
  32.                 Response.Write("successfully uploaded");  
  33.                  
  34.             }  
  35.             else  
  36.                 Response.Write("Error");  
  37.         }  
  38.     }  
  39. }  

Now, right click on your project name in Solution Explorer and add a new class. I have named it AmazonUploader.cs.

ASP.NET

The code for AmazonUploader.cs will be like below.

  1. using Amazon.S3;  
  2. using Amazon.S3.Transfer;  
  3.   
  4. namespace awsTestUpload  
  5. {  
  6.     public class AmazonUploader  
  7.     {  
  8.         public bool sendMyFileToS3(System.IO.Stream localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)  
  9.         {  
  10.             IAmazonS3 client = new AmazonS3Client(RegionEndpoint.APSouth1);  
  11.             TransferUtility utility = new TransferUtility(client);  
  12.             TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();  
  13.   
  14.             if (subDirectoryInBucket == "" || subDirectoryInBucket == null)  
  15.             {  
  16.                 request.BucketName = bucketName; //no subdirectory just bucket name  
  17.             }  
  18.             else  
  19.             {   // subdirectory and bucket name  
  20.                 request.BucketName = bucketName + @"/" + subDirectoryInBucket;  
  21.             }  
  22.             request.Key = fileNameInS3; //file name up in S3  
  23.             request.InputStream = localFilePath;  
  24.             utility.Upload(request); //commensing the transfer  
  25.   
  26.             return true//indicate that the file was sent  
  27.         }  
  28.     }  
  29. }  

Now, you have to set your AWS Secret Key Id and Secret Key in your webconfig file. Place the following code under <configurations> tag in webconfig file.

  1. <appSettings>  
  2.     <add key="AWSProfileName" value="Profile Name" />  
  3.     <add key="AWSAccessKey" value=" Your Secret Key Id " />  
  4.     <add key="AWSSecretKey" value="Your Secret Key " />  
  5.     <!--AWSProfileName is used to reference an account that has been registered with the SDK.  
  6. If using AWS Toolkit for Visual Studio then this value is the same value shown in the AWS Explorer.  
  7. It is also possible to register an account using the <solution-dir>/packages/AWSSDK-X.X.X.X/tools/account-management.ps1 PowerShell script  
  8. that is bundled with the nuget package under the tools folder.  
  9.   
  10.         <add key="AWSProfileName" value="" />  
  11. -->  
  12.   </appSettings>  

If you want to upload large files, add the following settings too in webconfig file all under <configuration> tag.

  1. <system.web>  
  2.     
  3.  <compilation debug="true" targetFramework="4.6" />  
  4.   <httpRuntime targetFramework="4.6" maxRequestLength="1048576" executionTimeout="3600" />  
  5. <pages>  
  6.     <controls>  
  7.       <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />  
  8.     </controls>  
  9.   </pages></system.web>  
  10.   <system.webServer>  
  11.   <security>  
  12.     <requestFiltering>  
  13.       <requestLimits maxAllowedContentLength="1073741824" />  
  14.     </requestFiltering>  
  15.   </security>  
  16.   
  17. </system.webServer>  

That’s it. Now, run the project.

Output

ASP.NET
Uploaded file in S3

ASP.NET