Before you use this class i recommend you to use an interface and inject it on your dependencies with your dependency injection system.
If you wanna an example of interface you can get:
public interface ICloudStorage
{
/// <summary>
/// Upload a new file to the cloud storage
/// </summary>
/// <param name="file">File to be uploaded</param>
/// <param name="folder">Folder where the file should be</param>
/// <returns>file location path</returns>
public Task<string> UploadFileAsync(IFormFile file, string? folder = null);
/// <summary>
/// delete a file that is on cloud storage by your path
/// </summary>
/// <param name="fullpath">path from root until the file</param>
/// <returns></returns>
public Task DeleteFileAsync(string fullpath);
}
and inject in your dependencies like in .NET CORE 7
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ICloudStorage, S3>();
Make sure you have your AWS credentials configured in your machine.
Now, add your settings to the appsettings.Development.json
like:
{
"AWS_S3": {
"Profile": "default",
"Region": "us-east-2"
}
}
the Profile
and Region
should be your bucket Profile
and Region
.
Then, let's install the needed packages:
installing the AWSSDK.S3
dotnet add package AWSSDK.S3
installing the AWSSDK.Extensions.NETCore.Setup
to setup dependency injection
dotnet add package AWSSDK.Extensions.NETCore.Setup
now, let's inject the necessary stuff to work with s3:
builder.Services.AddAWSService<IAmazonS3>();
and set the default aws credentials:
var awsOptions = builder.Configuration.GetAWSOptions("AWS_S3");
services.AddDefaultAWSOptions(awsOptions);
and, done.
in any of your controllers (for example) you can add the ICloudStorage
interface as parameter type, and you should have access to the methods successfully