What Do I Click Registering For Sat If I Am In Common Core
This article will learn how to upload , download and delete files from amazon AWS S3 Cloud Storage using ASP.Internet Cadre three.one
![](https://tutexchange.com/wp-content/uploads/2021/02/image-31.png)
What is Amazon S3?
Amazon S3 has a simple spider web services interface that you can utilise to store and call up whatever amount of information, at whatsoever time, from anywhere on the web.
https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html
- Creating application ASP.Net Core Application
- Installing packages from NuGet
- Creating a Saucepan
- View afterwards creating a bucket.
- Creating a User
- Adding a User to Group and assigning policy
- Created Table for Storing Documents
- Added Entity and DbContext form forth with interface and Concrete for Storing and Reading the documents
- AppSettings for Storing AccessKey and SecretKey configuring database connectedness string
- Creating Controller
- Upload File
- AllFiles
- Download file
- Delete file
Creating application ASP.NET Core Application
![](https://tutexchange.com/wp-content/uploads/2021/02/image.png)
Adjacent, nosotros are going to prepare Project Proper name WebStorageDemo and location.
In the terminal part, we will choose .Cyberspace Core framework and ASP.NET Cadre Version 5.0 every bit the framework for application and few advance settings for configuring and enabling docker we are not going to enable docker settings for this projection.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-2.png)
Now finally click on create button to create a project.
Project structure
The project structure generated co-ordinate to the configuration.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-3.png)
Later creating project next, we are going to install below bundle from NuGet Packages.
Installing a package from NuGet
1. WindowsAzure.Storage
![](https://tutexchange.com/wp-content/uploads/2021/02/image-4.png)
2. Microsoft.EntityFrameworkCore
![](https://tutexchange.com/wp-content/uploads/2021/02/image-5.png)
iii. Microsoft.EntityFrameworkCore.SqlServer
![](https://tutexchange.com/wp-content/uploads/2021/02/image-6.png)
After installing packages next, we will create a saucepan for that we must have an AWS account.
If you do not have an account, then create one account for free. https://aws.amazon.com/
I have already created an AWS account and logged in to the portal, for creating a bucket.
Creating a Saucepan
The saucepan is a virtual container where nosotros are going to store all objects.
For using Amazon S3 service, we must search S3 service in search.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-7.png)
After selecting S3 service, information technology redirects to buckets page.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-8.png)
Here for creating a bucket, we demand to click on Create bucket button.
For creating a bucket, we need to enter a unique bucket name and select region where you want this bucket to exist made.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-9.png)
Here nosotros are going to enter the name of the bucket (myawscorebucket) and so select region as the Asia Pacific (Mumbai) afterward selecting just scroll your page then you will find Block Public Admission settings for the bucket here for the demo I am going to uncheck all checkboxes you must uncheck it according to your demand.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-10.png)
Just scroll your page below you will find create bucket push but click on it to create a bucket.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-11.png)
View after creating a bucket
![](https://tutexchange.com/wp-content/uploads/2021/02/image-12.png)
Afterwards creating a bucket adjacent, we are going to create a user for we demand to search IAM (Identity and Admission Management).
Adding a User
![](https://tutexchange.com/wp-content/uploads/2021/02/image-13.png)
Later selecting IAM, yous will see below screen.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-14.png)
Subsequently clicking on Add together user, we volition add a user name and select Access blazon as shown below.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-15.png)
After filling in all details, click on the next permission push button.
Adding a User to Grouping and assigning policy
![](https://tutexchange.com/wp-content/uploads/2021/02/image-16.png)
We will create a group with the name AWSS3FullAccess and assign a policy (AmazonS3FullAccess) to access Amazon S3.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-17.png)
Merely click on Create grouping push button for creating a grouping. Next footstep volition exist making tags I will skip it, and the final screen will exist Review as shown below.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-18.png)
The review page will bear witness all details that you take configured but click on create a user information technology will create user successfully as shown below.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-19.png)
Now you have Access cardinal ID and Clandestine access primal for accessing S3 Services. Side by side, we have created a table in the database to store document details.
Created Tabular array for Storing Documents
Creating a table with name DocumentStore for storing certificate details.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-20.png)
Added Entity and DbContext class forth with interface and Concrete for Storing and Reading the document
![](https://tutexchange.com/wp-content/uploads/2021/02/image-21.png)
In this part kickoff, we have added the DocumentStore Entity.
using Arrangement; using Organisation.ComponentModel.DataAnnotations; using Arrangement.ComponentModel.DataAnnotations.Schema; namespace WebStorageDemo.Models { [Table("DocumentStore")] public grade DocumentStore { [Key] public int DocumentId { get; set; } public cord DocumentName { get; set up; } public string DocumentType { get; ready; } public DateTime CreatedOn { get; set; } } }
Side by side, nosotros accept added DbContext with proper noun BlobDbContext.
using Microsoft.EntityFrameworkCore; using WebStorageDemo.Models; namespace WebStorageDemo.Repository { public grade BlobDbContext : DbContext { public BlobDbContext(DbContextOptions<BlobDbContext> options) : base(options) { } public DbSet<DocumentStore> DocumentStore { get; gear up; } } }
After adding BlobDbContext side by side, we are going to add Interface and Physical in the Repository folder.
using System.Collections.Generic; using WebStorageDemo.Models; namespace WebStorageDemo.Repository { public interface IDocumentData { void Add together(DocumentStore documentStore); List<DocumentStore> GetDocumentStoresList(); void Delete(DocumentStore documentStore); DocumentStore GetDocumentbyDocumentId(int documentId); } }
AppSettings for Storing AccessKey and SecretKey and configuring database connectedness string
It is not recommended to store the keys in the appsettings.json file y'all tin employ the all-time methods bachelor for the demo I am storing keys in the appsettings.json file.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-22.png)
After setting keys in the appsettings.json file next, nosotros will configure entity framework core, appsettings and registering IDocumentData interface.
public void ConfigureServices(IServiceCollection services) { services.AddScoped<IDocumentData, DocumentData>(); var connection = Configuration.GetConnectionString("DatabaseConnection"); services.AddDbContext<BlobDbContext>(options => options.UseSqlServer(connection)); services.Configure<AppSettings>(Configuration.GetSection("AwsSettings")); services.AddControllersWithViews(); }
Everything is configured now let's Create Controller for Uploading, Downloading and Deleting files.
Creating Controller
We will create Controller With proper name DemoController with different action methods such as UploadFile, DeleteFile, DownloadFile and AllFiles.
If you want to access bucket and No one else has access rights then make CannedACL = S3CannedACL.Private.
NoACL | No Canned ACL is used. |
Private | Owner gets FULL_CONTROL. No i else has access rights (default). |
PublicRead | Possessor gets FULL_CONTROL and the anonymous principal is granted READ access. If this policy is used on an object, it tin can be read from a browser with no authentication. |
PublicReadWrite | Owner gets FULL_CONTROL, the anonymous principal is granted READ and WRITE access. This can be a useful policy to employ to a bucket, only is more often than not not recommended. |
AuthenticatedRead | Owner gets FULL_CONTROL, and whatever principal authenticated as a registered Amazon S3 user is granted READ access. |
BucketOwnerRead | Object Owner gets FULL_CONTROL, Bucket Possessor gets READ This ACL applies only to objects and is equivalent to private when used with PUT Bucket. You use this ACL to let someone other than the bucket owner write content (get full control) in the saucepan but still grant the bucket owner read admission to the objects. |
BucketOwnerFullControl | Object Owner gets FULL_CONTROL, Bucket Owner gets FULL_CONTROL. This ACL applies only to objects and is equivalent to individual when used with PUT Bucket. Yous apply this ACL to let someone other than the saucepan owner write content (get full control) in the bucket but nonetheless grant the saucepan possessor total rights over the objects. |
LogDeliveryWrite | The LogDelivery grouping gets WRITE and READ_ACP permissions on the saucepan. |
Reference Link :- https://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/T_Amazon_S3_Model_S3CannedACL.htm
Upload File
We will access 2 things in Controller AppSettings, IDocumentData from appsettings we volition go bucket proper noun, Admission key and Secret key, we will laissez passer Access key and Undercover key to BasicAWSCredentials method and and then set RegionEndpoint.
Subsequently that, we will get uploaded files details from IFromFile interface that we will assign to TransferUtilityUploadRequest form of AWS then finally call TransferUtility class and access UploadAsync method to upload file meanwhile we are going to shop all document details to the database.
[HttpGet] public IActionResult UploadFile() { return View(); } [HttpPost] public async Task<IActionResult> UploadFile(IFormFile file) { try { var bucketName = !string.IsNullOrWhiteSpace(_appSettings.FolderName) ? _appSettings.BucketName + @"/" + _appSettings.FolderName : _appSettings.BucketName; var credentials = new BasicAWSCredentials(_appSettings.AccessKey, _appSettings.SecretKey); var config = new AmazonS3Config { RegionEndpoint = Amazon.RegionEndpoint.APSouth1 }; using var client = new AmazonS3Client(credentials, config); await using var newMemoryStream = new MemoryStream(); wait file.CopyToAsync(newMemoryStream); var fileExtension = Path.GetExtension(file.FileName); var documentName = $"{GenerateId()}{fileExtension}"; // URL for Accessing Document for Demo var event = $"https://{bucketName}.s3.amazonaws.com/{documentName}"; var uploadRequest = new TransferUtilityUploadRequest { InputStream = newMemoryStream, Key = documentName, BucketName = bucketName, CannedACL = S3CannedACL.PublicRead }; var fileTransferUtility = new TransferUtility(client); await fileTransferUtility.UploadAsync(uploadRequest); DocumentStore documentStore = new DocumentStore() { CreatedOn = DateTime.Now, DocumentId = 0, DocumentName = documentName, DocumentType = file.ContentType }; _documentdata.Add(documentStore); } 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); } } return RedirectToAction("AllFiles"); }
Output
We are going to access the Demo/UploadFile path for uploading the file.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-23.png)
After uploading the file, we can run into in AWS S3 objects section as shown below.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-24.png)
While uploading information, we are storing file details in the database.
![](https://tutexchange.com/wp-content/uploads/2021/02/image-25.png)
All Files
In this part, we are going to show all files which are stored in the database along with download and delete characteristic.
public IActionResult AllFiles() { return View(_documentdata.GetDocumentStoresList()); }
![](https://tutexchange.com/wp-content/uploads/2021/02/image-26.png)
All Files View
@model Listing<DocumentStore> <table class="table table-striped"> <thead> <tr> <thursday>DocumentId</th> <th>DocumentName</th> <th>CreatedOn</thursday> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> @foreach (var data in Model) { <tr> <td>@data.DocumentId</td> <td>@data.DocumentName</td> <td>@information.CreatedOn</td> <td> <a grade="btn btn-success" href="/Demo/DownloadFile/@data.DocumentId">Download</a> </td> <td> <a grade="btn btn-danger" href="/Demo/DeleteFile/@data.DocumentId">Delete</a> </td> </tr> } </tbody> </table>
Download file
We have created the DownloadFile action method for downloading, which takes certificate id as an input parameter and then gets document details. From this certificate details, nosotros will accept certificate name and pass it to GetObjectAsync method, which will get an object from S3 Bucket which contains ResponseStream and objectResponse.Headers.ContentType.
public async Task<IActionResult> DownloadFile(int id) { endeavour { var getdocument = _documentdata.GetDocumentbyDocumentId(id); var credentials = new BasicAWSCredentials(_appSettings.AccessKey, _appSettings.SecretKey); var config = new AmazonS3Config { RegionEndpoint = Amazon.RegionEndpoint.APSouth1 }; using var client = new AmazonS3Client(credentials, config); var fileTransferUtility = new TransferUtility(client); var objectResponse = await fileTransferUtility.S3Client.GetObjectAsync(new GetObjectRequest() { BucketName = _appSettings.BucketName, Key = getdocument.DocumentName }); if (objectResponse.ResponseStream == null) { return NotFound(); } return File(objectResponse.ResponseStream, objectResponse.Headers.ContentType, getdocument.DocumentName); } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != zippo && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { throw new Exception("Check the provided AWS Credentials."); } else { throw new Exception("Fault occurred: " + amazonS3Exception.Message); } } }
Output
![](https://tutexchange.com/wp-content/uploads/2021/02/image-27.png)
Delete file
For Deleting file, we accept created a DeleteFile activeness method that takes document id equally an input parameter and then documents details. From this document details, we will take document name and pass it to DeleteObjectAsync method which will delete an object from S3 Saucepan while we are going call delete method from DocumentData class delete the file from the database.
public async Task<IActionResult> DeleteFile(int id) { try { var getdocument = _documentdata.GetDocumentbyDocumentId(id); _documentdata.Delete(getdocument); var credentials = new BasicAWSCredentials(_appSettings.AccessKey, _appSettings.SecretKey); var config = new AmazonS3Config { RegionEndpoint = Amazon.RegionEndpoint.APSouth1 }; using var client = new AmazonS3Client(credentials, config); var fileTransferUtility = new TransferUtility(customer); await fileTransferUtility.S3Client.DeleteObjectAsync(new DeleteObjectRequest() { BucketName = _appSettings.BucketName, Central = getdocument.DocumentName }); } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { throw new Exception("Cheque the provided AWS Credentials."); } else { throw new Exception("Fault occurred: " + amazonS3Exception.Bulletin); } } return RedirectToAction("AllFiles"); }
Before delete
![](https://tutexchange.com/wp-content/uploads/2021/02/image-28.png)
Later on delete
![](https://tutexchange.com/wp-content/uploads/2021/02/image-29.png)
Output
![](https://tutexchange.com/wp-content/uploads/2021/02/image-30.png)
In this commodity, we have learned how to upload , download and delete files from amazon AWS S3 Deject Storage using ASP.NET Cadre in simple steps hope y'all have like it please share it let others learn from it.
What Do I Click Registering For Sat If I Am In Common Core,
Source: https://tutexchange.com/uploading-downloading-and-deleting-files-in-aws-s3-cloud-storage-using-asp-net-core/
Posted by: kohlersampe1938.blogspot.com
0 Response to "What Do I Click Registering For Sat If I Am In Common Core"
Post a Comment