DEV Community

Alexi Tomala
Alexi Tomala

Posted on

Uploading Files to Amazon S3 in ASP.NET Core with Razor Pages

In this post we are going to explore how to upload file
to our AWS S3 repository from an ASP.NET Core with Razor Pages app.

In this case we make use of Visual studio for the creation and configuration of the solution:
We select and create the Asp.Net project type.
ASP.NET CORE Web App

Created the solution we install the package nuget AWSSDK.S3
from the AwsS3 library

AWSs3

For this solution we are going to implement the repository pattern and start creating the interface for the file upload.

namespace WebUploadFileS3.Interfaces
{
    public interface IRepositoryS3
    {
        Task<string> UploadFileAsync(IFormFile file);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now create the class to implement the file upload method

using WebUploadFileS3.Interfaces;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;

namespace WebUploadFileS3.implementation
{
    public class RespositoryS3 : IRepositoryS3
    {
        private readonly IAmazonS3 _s3Client;
        private readonly string _bucketName;

        public RespositoryS3(IConfiguration configuration)
        {
            var accessKey = configuration["AWS:AccessKey"];
            var secretKey = configuration["AWS:SecretKey"];
            var region = configuration["AWS:Region"];
            _bucketName = configuration["AWS:BucketName"];

            _s3Client = new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.GetBySystemName(region));
        }
        public async Task<string> UploadFileAsync(IFormFile file)
        {
            using var newMemoryStream = new MemoryStream();
            file.CopyTo(newMemoryStream);

            var request = new PutObjectRequest
            {
                BucketName = _bucketName,
                Key = file.FileName,
                InputStream = newMemoryStream,
                ContentType = file.ContentType,
                AutoCloseStream = true
            };
            await _s3Client.PutObjectAsync(request);
            return file.FileName;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

En el archivo appsettings.json adicionar la credenciales de acceso al servicio AWS S3

"AWS": {
    "AccessKey": "AccessKey",
    "SecretKey": "SecretKey",
    "BucketName": "bucketnet",
    "Region": "Region-1"
  }
Enter fullscreen mode Exit fullscreen mode

Continue adding dependency in Program.cs or Startup file

using Microsoft.AspNetCore.Http.Features;
using WebUploadFileS3.implementation;
using WebUploadFileS3.Interfaces;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IRepositoryS3, RespositoryS3>();
Enter fullscreen mode Exit fullscreen mode

Finally in the razor page view create file upload form

<div class="text-center">

    @{ ViewData["Title"] = "Upload File"; }
    <h2>Upload File</h2> 
    <form asp-controller="Home" asp-action="Upload" enctype="multipart/form-data" method="post"> 
        <div class="form-group">
            <label for="file">Select to file:</label> 
            <input type="file" name="file" id="file" class="form-control" /> 
        </div>
        <br />
        <button type="submit" class="btn btn-primary">Upload</button>
    </form>
</div>
Enter fullscreen mode Exit fullscreen mode

Check out the source code in: https://github.com/ajtomala/WebUploadFileS3

Please let me know your questions

Top comments (0)