Logo

dev-resources.site

for different kinds of informations.

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

Published at
1/7/2025
Categories
aws
aspdotnet
tutorial
s3
Author
ajtomala
Categories
4 categories in total
aws
open
aspdotnet
open
tutorial
open
s3
open
Author
8 person written this
ajtomala
open
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

aspdotnet Article's
30 articles in total
Favicon
Uploading Files to Amazon S3 in ASP.NET Core with Razor Pages
Favicon
Managing Relationships, Migrations, and Performance Optimization in ASP.NET Core MVC
Favicon
DevExpress - Enhancing ASP.NET Web Forms with the ASPxGridView Control
Favicon
DevExpress - Simplifying Server-to-Client Data Transfer with ASPxCallback JSProperties
Favicon
🚀 [ASP.NET] How to design API allowed client specific fields?
Favicon
Web application translation in two ways.
Favicon
[Boost]
Favicon
[Boost]
Favicon
Command Pattern with Undo and Redo in C#.NET
Favicon
Server Sent Events in ASP.NET Core
Favicon
Everything New in .NET 9: The Ultimate Developer's Guide
Favicon
Is .NET 9 beneficial for Blazor?
Favicon
The Guardian Middleware: Handling Errors Globally in ASP.NET
Favicon
.NET Aspire: A Game-Changer for Cloud-Native Development Services
Favicon
Top 20+ Full-stack Projects For Beginners in C#, ASP.NET , .NET CORE
Favicon
🔐 How to Implement OAuth 2.0 Authentication in ASP.NET Core with External APIs
Favicon
Performance Optimization Techniques for ASP.NET Core Applications
Favicon
Patterns for Routing in ASP.NET Core minimal APIs
Favicon
How to prevent XSS Attacks in ASP.NET Core Web API
Favicon
MyHotixRestaurant
Favicon
Microservices using ASP.NET Core, Ocelot, MongoDB and JWT
Favicon
suggest design warehouse management
Favicon
Maximizing ASP.NET Potential through Azure Development Services
Favicon
10 Lessons I Learned from Using Aspire in Production
Favicon
Logging in ASP.NET Core
Favicon
What is ASP.NET used for in software development?
Favicon
Concepts of a Ticket in ASP.NET Identity
Favicon
Building a Scalable Multi-Tenant Community Management System with ASP.NET and Angular
Favicon
How to Manage Persistent Connections in a WhatsApp-like Chat Application Using ASP.NET SignalR and EF Core?
Favicon
Deep Dive ASP.NET Core Middleware : Part 1

Featured ones: