I am tired of all these \"upload to S3\" examples and tutorials that don\'t work , can someone just show me an example that simply works and is super easy?
The solution of @docesam is for an old version of AWSSDK. Here is an example with the latest documentation of AmazonS3:
1) First open Visual Studio (I'm using VS2015) and create a New Project -> ASP.NET Web Application -> MVC.
2) Browse in Manage Nuget Package , the package AWSSDK.S3 and install it.
3) Now create a class named AmazonS3Uploader, then copy and paste this code:
using System;
using Amazon.S3;
using Amazon.S3.Model;
namespace AmazonS3Demo
{
public class AmazonS3Uploader
{
private string bucketName = "your-amazon-s3-bucket";
private string keyName = "the-name-of-your-file";
private string filePath = "C:\\Users\\yourUserName\\Desktop\\myImageToUpload.jpg";
public void UploadFile()
{
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
try
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
ContentType = "text/plain"
};
PutObjectResponse response = client.PutObject(putRequest);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
throw new Exception("Check the provided AWS Credentials.");
}
else
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
}
}
}
4) Edit your Web.config file adding the next lines inside of :
5) Now call your method UploadFile from HomeController.cs to test it:
public class HomeController : Controller
{
public ActionResult Index()
{
AmazonS3Uploader amazonS3 = new AmazonS3Uploader();
amazonS3.UploadFile();
return View();
}
....
6) Find your file in your Amazon S3 bucket and that's all.
Download my Demo Project