DEV Community

Anna Aitchison
Anna Aitchison

Posted on • Edited on

8 2

How to Upload files to S3 in a C# ASP .NET Core App

The instructions in this article are designed for a C# ASP .NET MVC application. They should work elsewhere are with tweaks for your situation. This assumes that your AWS creds are already setup. It's based on a Microsoft article about file uploads with tweaks for the s3 upload.

Add dependency

Add the NuGet module AWSSDK.S3 to your project

Add the data class

Create a file with this content

using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;
using System;
using System.IO;
using System.Threading.Tasks;

namespace YOUR_NAMESPACE
{
    public class S3Upload
    {
        private static readonly RegionEndpoint bucketRegion = RegionEndpoint.EUWest2;
        private static IAmazonS3 s3Client;

        public static async Task UploadFileAsync(Stream FileStream, string bucketName, string keyName)
        {
            s3Client = new AmazonS3Client(bucketRegion);
            var fileTransferUtility = new TransferUtility(s3Client);
            await fileTransferUtility.UploadAsync(FileStream, bucketName, keyName);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Add a new modal

Add a new modal called FileUploadFormModal.cs to your project with this content

public class FileUploadFormModal
{
    [Required]
    [Display(Name="File")]
    public IFormFile FormFile { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Add a view

Create a view called FileUploadForm.cshtml with this content in Views/Home

@model FileUploadFormModal
<form enctype="multipart/form-data" method="post">
    <dl>
        <dt>
            <label asp-for="FileUploadFormModal.FormFile"></label>
        </dt>
        <dd>
            <input asp-for="FileUploadFormModal.FormFile" type="file">
        </dd>
    </dl>
    <input asp-page-handler="Upload" class="btn" type="submit" value="Upload">
</form>
Enter fullscreen mode Exit fullscreen mode

Edit HomeController.cs controller

Add a using statement for the data class and add the following code to the HomeController.cs

public async Task<IActionResult> FileUploadForm()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> FileUploadForm(FileUploadFormModal FileUpload)
{
    using (var memoryStream = new MemoryStream())
    {
        await FileUpload.FormFile.CopyToAsync(memoryStream);

        // Upload the file if less than 2 MB
        if (memoryStream.Length < 2097152)
        {
            await S3Upload.UploadFileAsync(memoryStream, "YOUR_BUCKET_NAME", "YOUR_KEY_NAME");
        }
        else
        {
            ModelState.AddModelError("File", "The file is too large.");
        }
    }

    return View();
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay