World is now on Opti ID! Learn more

Darren Sunderland
Apr 20, 2018
  563
(0 votes)

Write uploaded media files to Amazon S3

We recently had a need to allow the end users of our website to upload images as part of a competition.  As the images are not part of the website content it seemed illogical to save the data on the EpiServer platform, as this would use up our content item space.  After thinking through our options, we decided to write the uploaded images to an Amazon S3 bucket.

Below are the steps we followed to get our site writing to S3 – this has been tested in EpiServer 10 and above:

Add required packages to the solution

Using NuGet, install the following packages to connect to S3

  • AWSSDK.S3
  • AWSSDK.Core

Create a new class in your solution to handle the Amazon connection and writing:

using System.IO;
using Amazon;
using Amazon.Runtime;
using Amazon.S3;

namespace MyCMS
{
    public class AmazonS3Handler
    {
        private static string accessKey
        {
            get { return "ACCESS_KEY"; }
        }

        private static string secretKey
        {
            get { return "ACCESS_SECRET"; }
        }

        private static AmazonS3Client GetClient()
        {
            AmazonS3Config config = new AmazonS3Config
            {
                RegionEndpoint = RegionEndpoint.EUWest1
            };

            var creds = new BasicAWSCredentials(accessKey, secretKey);
            AmazonS3Client clientout = new AmazonS3Client(creds, config);

            return clientout;
        }

        /// <summary>
        /// This method controls the file writing to the S3 bucket
        /// </summary>
        /// <param name="bucketname">String containing the name of the S3 Bucket</param>
        /// <param name="filename">String containing the name for the artefact in S3</param>
        /// <param name="mimetype">String containing the file extension type</param>
        /// <param name="filecontent">Byte Array containing the content of the file</param>
        public static void CreateMediaFile(string bucketname, string filename, string mimetype, byte[] filecontent)
        {
            var client = GetClient();

            var request = new Amazon.S3.Model.PutObjectRequest
            {
                BucketName = bucketname,
                Key = filename,
                ContentType = mimetype,
                InputStream = new MemoryStream(filecontent)
            };
            client.PutObject(request);
        }
    }
}

Create a new page type to handle the user uploads

There are no specific property requirements for the new page type model.

In the new page type view, use HTML5 file upload component to allow the users to select and upload a file, see example:

<form enctype="multipart/form-data" method="post">
	<label for="fileUpload">Click or Drop your receipt here to upload it</label>
	<input type="file" id="fileUpload" name="fileUpload" multiple="multiple">
	<br />
	<input type="submit" value="Upload Files" />
</form>

In the new page type controller action method, use the following code to read the uploaded files and write them to S3

string bucketname = "BUCKET_NAME";
string filename = "";
string mimetype = "";

for (int i = 0; i < Request.Files.Count; i++)
{
	HttpPostedFileBase file = Request.Files[i];
	int fileLen = file.ContentLength;

	if (fileLen != 0)
	{
		string extension = Path.GetExtension(file.FileName);
		if ((extension.ToUpper() == "JPG") || (extension.ToUpper() == "JPEG"))
		{
			mimetype = "image/jpeg";
		}
		else if (extension.ToUpper() == "PNG")
		{
			mimetype = "image/png";
		}
		else if (extension.ToUpper() == "GIF")
		{
			mimetype = "image/gif";
		}
		
		byte[] input = new byte[fileLen];

		var fileContent = file.InputStream;
		fileContent.Read(input, 0, fileLen);

		filename = file.FileName;
		AmazonS3Handler.CreateMediaFile(bucketname, filename, mimetype, input);
	}
}

The above code snippets provide a guide on how to write to S3.  To use this in a full EpiServer solution the following points should be considered:

  1. Amending the Access Key and Access Secret properties to read the values from a configuration source, this would allow different values to be used for different environments.
  2. Creating a method to generate a unique file name for the uploaded file, this would prevent issues of different users uploading files with the same name (e.g. image1.jpg).
Apr 20, 2018

Comments

Please login to comment.
Latest blogs
Make Global Assets Site- and Language-Aware at Indexing Time

I had a support case the other day with a question around search on global assets on a multisite. This is the result of that investigation. This co...

dada | Jun 26, 2025

The remote server returned an error: (400) Bad Request – when configuring Azure Storage for an older Optimizely CMS site

How to fix a strange issue that occurred when I moved editor-uploaded files for some old Optimizely CMS 11 solutions to Azure Storage.

Tomas Hensrud Gulla | Jun 26, 2025 |

Enable Opal AI for your Optimizely products

Learn how to enable Opal AI, and meet your infinite workforce.

Tomas Hensrud Gulla | Jun 25, 2025 |

Deploying to Optimizely Frontend Hosting: A Practical Guide

Optimizely Frontend Hosting is a cloud-based solution for deploying headless frontend applications - currently supporting only Next.js projects. It...

Szymon Uryga | Jun 25, 2025

World on Opti ID

We're excited to announce that world.optimizely.com is now integrated with Opti ID! What does this mean for you? New Users:  You can now log in wit...

Patrick Lam | Jun 22, 2025

Avoid Scandinavian Letters in File Names in Optimizely CMS

Discover how Scandinavian letters in file names can break media in Optimizely CMS—and learn a simple code fix to automatically sanitize uploads for...

Henning Sjørbotten | Jun 19, 2025 |