Guest User

Guest User

  • Tech Writer
  • 515
  • 47.1k

About AWS S3 Upload, Fetch, Download & Delete through MVC

Jul 2 2021 9:20 AM

Hello,

Hope everyone is doing fine.

I am working on project with MVC and SQL database, where I am storing files on aws s3.

I am looking for Upload, Fetch, Download & Delete code from aws s3.

I got Upload code , but it says - Access Denied. Following is the Upload code :

[HttpPost]
        public ActionResult Index(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("~/MemoryImage"), Path.GetFileName(file.FileName));
                    var filePath = HttpContext.Server.MapPath("~/MemoryImage/" + file.FileName + "");
                    file.SaveAs(filePath);
                    var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                    {
                        BucketName = bucketName,
                        FilePath = filePath,
                        StorageClass = S3StorageClass.StandardInfrequentAccess,
                        PartSize = 6291456, // 6 MB.  
                        Key = keyName,
                        CannedACL = S3CannedACL.PublicReadWrite
                    };
                    fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
                    fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
                    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");
        }

plz let me know if any solution.

Thank You !

 


Answers (2)