When trying to upload an image from the website to the AWS bucket I get an ajax error. However, when I run the application from visual studio, it loads without problems.
The code C# I use in the controller is the following:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
var fileTransferUtility = new TransferUtility(s3Client);
try
{
if (file.ContentLength > 0)
{
var filePath = Path.Combine(Server.MapPath("~/"), Path.GetFileName(file.FileName));
var fileTransferUtilityRequest = new TransferUtilityUploadRequest
{
BucketName = bucketName,
FilePath = filePath,
StorageClass = S3StorageClass.StandardInfrequentAccess,
Key = keyName,
CannedACL = S3CannedACL.PublicRead
};
fileTransferUtility.Upload(fileTransferUtilityRequest);
fileTransferUtility.Dispose();
}
ViewBag.Message = "File Uploaded Successfully!!";
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
ViewBag.Message = "Check the provided AWS Credentials.";
}
else
{
ViewBag.Message = "Error occurred: " + amazonS3Exception.Message;
}
}
return RedirectToAction("Index");
}
What I have tried:
I have tried other options that I found online with no results. The region is USEast2 and the code is as follows:
IAmazonS3 client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
FileInfo localFile = new FileInfo(@"c:\test.txt");
string destPath = @"folder\sub-folder\test.txt";
S3FileInfo s3File = new S3FileInfo(client, "my-bucket-name", destPath);
if (!s3File.Exists)
{
using (var s3Stream = s3File.Create())
{
localFile.OpenRead().CopyTo(s3Stream);
}
}
Another option that I have tried is with the following code and the error is presented on the line
InputStream = localFile.OpenRead(),
There the error says that it cannot find the file path
PutObjectRequest request = new PutObjectRequest()
{
InputStream = localFile.OpenRead(),
BucketName = bucketName,
Key = path
};
PutObjectResponse response = client.PutObject(request);
I bring the image with this code, where I capture the image in the upload input
FileInfo localFile = new FileInfo(image.FileName);