DEV Community


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

ara225 profile image Anna Aitchison Updated on ・2 min read

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;

    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
    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">
            <label asp-for="FileUploadFormModal.FormFile"></label>
            <input asp-for="FileUploadFormModal.FormFile" type="file">
    <input asp-page-handler="Upload" class="btn" type="submit" value="Upload">
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();

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");
            ModelState.AddModelError("File", "The file is too large.");

    return View();
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Editor guide