Search Sreeni's Insights

Filter by content type
cloud September 15, 2015 7 min read

How to store files in Azure Blob Storage from ASP.NET?

Storing files in Azure Blob Storage from ASP.NET, including containers, validation, uploads, private file serving, and separating file metadata.

Share:

How to store files in Azure Blob Storage from ASP.NET?

Applications are receiving documents, images and exports from users. Keeping all these files on the web server looks easy in the beginning, but the disk belongs to one instance and can disappear when the instance is replaced. As the application is growing, local files are creating deployment, backup and scaling blind spots, and the customer is directly seeing missing images.

Azure Blob Storage is designed to store large amounts of unstructured data. In this article, we are going to see how an ASP.NET MVC 5 application can upload a file to a block blob, keep its metadata in the application, and download it safely.

We can upload files through two common paths:

ApproachProsCons
ASP.NET server-side upload+ Central validation and authorization<br>+ Simple first implementation− Uses web server bandwidth<br>− Large files increase request time
Direct upload with a signed URL+ Reduces web server transfer<br>+ Better for larger files− More client and expiry handling<br>− Requires careful permission design

TL;DR Summary

  • Blob Storage keeps files outside the web server filesystem.
  • The application should store the blob name and business metadata, not the binary in a relational row.
  • Validate size, extension and content before uploading.
  • Use a private container when files are not public.
  • Keep storage credentials outside source control.
  • A blob upload is not complete until we confirm the expected blob exists.

Challenges

Local disk does not scale

When a user uploads a news image to one web instance, the image may not exist on another instance. A later request can return a missing file and the customer will see a broken article. It is a classical example of a hidden dependency created by local storage.

File safety

A file name comes from an external user and must not become a path on the server. A malicious file can also have a trusted extension but unexpected content. We must validate the request and store blobs with generated names, otherwise the upload boundary becomes a security risk.

Metadata and lifecycle

The binary file is only one part of the business information. We may need the article identifier, content type, creator and upload date. Keeping this metadata separately allows us to search and clean unused files without scanning every blob.

What is Azure Blob Storage?

Azure Blob Storage is an object storage service for binary large objects such as images, documents and backups.

In simple terms, a storage account contains containers, and a container contains blobs. A block blob is a good choice for ordinary uploaded files. The web application can use the blob key as a reference while the storage service handles durable object storage.

Why use Blob Storage?

Blob Storage separates file capacity from web compute capacity. We can add a web instance without copying a local uploads folder to the new machine. It is like keeping newspaper photographs in a shared archive instead of one editor’s desk, the article system stores the reference and everyone can reach the same archive.

How to upload a blob?

The following diagram depicts an ASP.NET upload request and the storage account,

ASP.NET upload to Azure Blob Storage
ASP.NET upload to Azure Blob Storage

Option1: ASP.NET server-side upload

Steps to Implement:

Follow the following instructions to upload files from ASP.NET MVC.

  • Create an Azure Storage account and a private blob container.

    Storage account: <storage account name>
    Container: <container name>
    Access: Private
  • Install the WindowsAzure.Storage package.

    Install-Package WindowsAzure.Storage
  • Add the storage connection string to the application configuration, and replace the input place holders with actual values.

    <connectionStrings>
      <add name="StorageConnection"
           connectionString="DefaultEndpointsProtocol=https;AccountName=<account-name>;AccountKey=<account-key>" />
    </connectionStrings>
  • Create a storage client and select the blob container.

    CloudStorageAccount account =
        CloudStorageAccount.Parse(
            ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
    CloudBlobClient client = account.CreateCloudBlobClient();
    CloudBlobContainer container = client.GetContainerReference("<container-name>");
    container.CreateIfNotExists();
  • Validate the upload before using the original file name.

    if (file == null || file.ContentLength == 0)
        return new HttpStatusCodeResult(400, "File is required");
    
    if (file.ContentLength > 5 * 1024 * 1024)
        return new HttpStatusCodeResult(400, "File is too large");
  • Generate a blob name and upload the content.

    string blobName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
    CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
    blob.Properties.ContentType = file.ContentType;
    blob.UploadFromStream(file.InputStream);
  • Save the blob name and article identifier in the application database.

    attachment.BlobName = blobName;
    attachment.ArticleId = articleId;
    db.Attachments.Add(attachment);
    db.SaveChanges();
  • Just to pulse check, retrieve the blob properties after upload.

    CloudBlockBlob uploaded = container.GetBlockBlobReference(blobName);
    uploaded.FetchAttributes();

    Note: Validate the permitted content types on the server, not only by trusting the browser value. Replace the input place holders with actual values and do not put storage account keys in source control.

  • Download the blob through an authorized controller action, or create a short-lived shared access signature when a direct URL is required.

    Response.ContentType = uploaded.Properties.ContentType;
    uploaded.DownloadToStream(Response.OutputStream);

Option2: Direct upload with a signed URL

For a larger file workflow, the server can authorize a short-lived shared access signature and let the client upload to the permitted blob location. The API should still record the upload and validate the result, because a signed URL is a limited capability, not proof that the business record is complete.

Upload design considerations

The database transaction and blob upload are two separate operations. If the blob succeeds and the database fails, an orphan blob can remain. If the database succeeds and the upload fails, the metadata points to nothing. A practical process is to mark the metadata as pending, upload the blob, then mark it ready, and run a cleanup process for old pending entries.

Use a private container for customer documents and check authorization before returning a blob. A public container may be acceptable for a deliberately public image, but it should be a conscious business decision. The storage account key has broad access, so use a managed configuration approach and rotate it according to the organization’s security process.

Do not use the original file name as the blob key even when it appears harmless. Two users can upload image.png, and special path characters can make logs and cleanup confusing. Keep the original name as display metadata only, generate the storage name, and record the content type after server-side validation.

Validating and serving files

Let us discuss the validation which should happen before the stream is going to Blob Storage,

private static readonly HashSet<string> AllowedExtensions =
    new HashSet<string>(StringComparer.OrdinalIgnoreCase)
    {
        ".png", ".jpg", ".jpeg", ".pdf"
    };

private bool IsAllowed(HttpPostedFileBase file)
{
    string extension = Path.GetExtension(file.FileName);
    return AllowedExtensions.Contains(extension)
        && file.ContentLength <= 5 * 1024 * 1024;
}

The extension check is only one check, it is not a proof that the content is safe. For sensitive workflows we should inspect the file signature, virus scan it and keep it private until the scan is completed. Otherwise, a file which is having a trusted extension can become a security incident.

When the browser needs to download a private file, the controller should first check the user’s permission, then stream the blob or issue a short-lived Shared Access Signature (SAS). Do not put the storage account key into the browser. The application is the gatekeeper, the storage key is having much more permission than one customer should have.

Must Do and Don’ts

  • Must Do: Generate a blob name with an identifier, and save original name as metadata.
  • Must Do: Store article identifier, content type, size and upload status in the application database.
  • Must Do: Configure lifecycle cleanup for pending or orphaned blobs.
  • Don’t: Trust file.ContentType from the browser as the only security check.
  • Don’t: Return a public URL for customer documents unless this is a deliberate business decision.
  • Keep in mind that: Blob upload and database save are two operations, so a reconciliation process is required.

For a news article image, the article record can first be marked as Pending, then the image is uploaded, scanned and linked, and finally the record is marked Ready. If the upload is failing, a scheduled cleanup can find pending records older than <pending file age> and remove the orphan blob. Use a placeholder until the retention value is confirmed, [confirm: pending blob retention period].

Wrap up

In this article, we have looked at why local files do not scale, how to create a blob container, validate and upload a file, serve private files and keep metadata separate. I hope this article provided you some insights into Azure Blob Storage. In the next article, I will walk you through sending and receiving messages with Azure Service Bus queues.

Related Posts