Simple Steps to Upload Files to Azure Blob Storage in Blazor App
Tags: blazor, csharp, dotnet, webdev
Published: 2021-11-24 15:55:52

---
title: Simple Steps to Upload Files to Azure Blob Storage in Blazor App
published: true
date: 2021-11-24 11:55:35 UTC
tags: blazor, csharp, dotnet, webdev
canonical_url: https://www.syncfusion.com/blogs/post/simple-steps-to-upload-files-to-azure-blob-storage-in-blazor-app.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cuaxa3ue92x6xc9mql1q.png
---

[Cloud storage](https://en.wikipedia.org/wiki/Cloud_storage "Link to the Wikipedia page for Cloud storage") is a service that allows users to store any digital files in a remote server, from which they can be easily accessed by any device.

[Azure Blob Storage](https://en.wikipedia.org/wiki/Microsoft_Azure "Link to the Wikipedia page for Microsoft Azure") is a service that enables you to upload and store large amounts of files in the cloud. It allows you to store your data cost-effectively while keeping it easily accessible using code or a direct storage client library.

Our Syncfusion [Blazor File Upload](https://www.syncfusion.com/blazor-components/blazor-file-upload "Link to the Blazor File Upload component") component can help upload one or more images, documents, audio, video, and other files to a server. It is an extended version of the HTML 5 upload component (<input type=” file”>). Its rich feature set includes multiple-file selection, progress bars, auto uploading, drag and drop, folder (directory) uploading, file validation, and more.

In this article, we will learn how to upload files to Azure Blob Storage using the Syncfusion Blazor File Upload component by looking at code examples.

We are going to divide the article into the following sections:

- [Creating Azure storage](#creating-azure-storage).
- [Uploading files to Azure with ASP.NET Core-hosted Blazor WebAssembly (WASM)](#upload-files-to-azure-with-asp-net-core-hotsed-blazor-webassembly).

## Prerequisites

- [Azure Storage](https://portal.azure.com/#home "Link to Microsoft Azure Portal").
- [Visual Studio 2019 and above.](https://visualstudio.microsoft.com/vs/ "Link to Visual Studio")
- [.NET Core 3.0 and above.](https://dotnet.microsoft.com/download/dotnet-core/3.0 "Link to .NET Core 3.0")

## Creating Azure storage

First, sign in to the [Azure portal](https://portal.azure.com/#home "Link to Microsoft Azure Portal") to create a storage account. If you don’t have a subscription, [create a free subscription account](https://azure.microsoft.com/en-in/free/ "Link to free subscription of the Microsoft Azure") and follow these steps:

**Step 1** : Select the **Storage accounts** option from the portal menu at the top.

**![Select the Storage accounts option](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Select-the-Storage-accounts-option-1.png)Step 2:** Then, on the **Storage accounts** page, select **Create.**

![On the Storage accounts page, select Create](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/On-the-Storage-accounts-page-select-Create-1.png)Options for your new storage account will be listed on the **Create a storage account** page.

**![Create a storage account page](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Create-a-storage-account-page-1.png)Step 3:** In the Basics tab, provide the following basic details of your storage account:

- The existing resource group (or create a new one).
- The name of your storage account.
- The region, performance, and redundancy.

![Fill up the details in the Create a storage account page](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Fill-up-the-details-in-the-Create-a-storage-account-page-1.png)

**Note:** The check box **Make read access to data available in the event of regional unavailability** will be checked by default.

**Step 4:** In the other tabs, don’t change anything. Click  **Next**  until you reach the **Review+Create** tab. Then, your validation will pass. Refer to the following screenshot.

**![Validation passed](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Validation-passed.png)**

**Note:** For more details about the options in the other tabs, refer to [Create a storage account documentation](https://docs.microsoft.com/en-us/azure/storage/common/storage-account-create?tabs=azure-portal#create-a-storage-account-1 "Documentation link to Create a storage account on Azure Blob").

**Step 5:** Now, click the **Create**  and wait for the deployment to complete. After deployment, you will see a screen like in the following screenshot.

**![Click the Create button and wait for some time to complete our deployment process](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Click-the-Create-button-and-wait-for-some-time-to-complete-our-deployment-process.png)Step 6:** After successful deployment, click  **Go to resource** to see your storage.

![Click on the Go to resource option](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Click-on-the-Go-to-resource-option.png)Now, your storage will look like the following screenshot.

**![Created Storage account](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Created-Storage-account.png)Step 7:** From the left portal menu, select  **Access keys** and copy your **Key** and **Connection string**. We will use them later in our application.

![Select the Access keys option to get your keys and connection string.](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Select-the-Access-keys-option-to-get-your-keys-and-connection-string..png)

## Upload files to Azure with ASP.NET Core-hosted Blazor WebAssembly (WASM)

[Create an ASP.NET Core-hosted Blazor WebAssembly app and add the required model and controller classes](https://docs.microsoft.com/en-us/aspnet/core/blazor/tooling?view=aspnetcore-3.1&pivots=windows "Tooling for ASP.NET Core Blazor"). We now have three project files inside the solution:

**Client:** Contains the client-side code and the pages that will be rendered in the browser.

**Server:** Contains the server-side code, such as DB-related operations and the Web API.

**Shared:** Contains the shared code that can be accessed at both the client and server.

### Add Blazor File Upload component in the client project

In the client project, add the Syncfusion Blazor File Upload component in the **Index.razor** page under the **Pages** folder. For more details, refer to the [Getting Started with Blazor File Upload Component](https://blazor.syncfusion.com/documentation/file-upload/getting-started "Documentation link to getting started with Blazor File Upload component") documentation.

The following code renders the Blazor File Upload component.

```html
<SfUploader AutoUpload="true" Multiple="false" ID="UploadFiles" MaxFileSize="5000000">
</SfUploader>
```

### Add upload handler to the server project

**Step 1:**  Now, include the connection string details in the **appsettings.json** file. Refer to the following screenshot.

![Include the connection string details in the appsettings.json file](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Include-the-connection-string-details-in-the-appsettings.json-file-1.png)You can get the connection string in the **Access keys**  section of your storage account. Refer to the following screenshot.

![Select the Access keys option to get your keys and connection string.](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Select-the-Access-keys-option-to-get-your-keys-and-connection-string..png) **Step 2:**  Then, install the **Azure.Storage.Blob** library to work with the **Azure Storage Blob service**.

**![Install the Azure.Storage.Blob library](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Install-the-Azure.Storage.Blob-library.png)Step 3:** Add the **Save** action controller in the **UploadAzureController** file under the **Controllers** folder.

**Step 4:** In the **UploadAzureController,** extract the Azure connection string from the **appsettings.json** file and store it in the private variable ( **azureConnectionString** ).  
Refer to the following code.

```csharp
[Route("api/[controller]")]
[ApiController]
public class UploadAzureController : ControllerBase
{
    private readonly string azureConnectionString;
    public UploadAzureController(IConfiguration configuration)
    {
        azureConnectionString = configuration.GetConnectionString("AzureConnectionString");
    }
}
```

**Step 5:** Now, add the Upload action to upload the files to the Azure Blob storage.

```csharp
[HttpPost("[action]")]
public async Task Upload(IList<IFormFile> UploadFiles)
{
    try
    {
        foreach (var files in UploadFiles)
        {
            // Azure connection string and container name passed as an argument to get the Blob reference of the container.
            var container = new BlobContainerClient(azureConnectionString, "upload-container");

            // Method to create our container if it doesn’t exist.
            var createResponse = await container.CreateIfNotExistsAsync();

            // If container successfully created, then set public access type to Blob.
            if (createResponse != null && createResponse.GetRawResponse().Status == 201)
                await container.SetAccessPolicyAsync(Azure.Storage.Blobs.Models.PublicAccessType.Blob);

            // Method to create a new Blob client.
            var blob = container.GetBlobClient(files.FileName);

            // If a blob with the same name exists, then we delete the Blob and its snapshots.
            await blob.DeleteIfExistsAsync(Azure.Storage.Blobs.Models.DeleteSnapshotsOption.IncludeSnapshots);

            // Create a file stream and use the UploadSync method to upload the Blob.
            using (var fileStream = files.OpenReadStream())
            {
                await blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType = files.ContentType });
            }
        }
    }
    catch (Exception e)
    {
        Response.Clear();
        Response.StatusCode = 204;
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
    }
}
```

**Step 6:** Then, add the upload action URL to the Syncfusion Blazor File Upload component.

```html
<SfUploader AutoUpload="true" Multiple="false" ID="UploadFiles" MaxFileSize="5000000">
    <UploaderAsyncSettings SaveUrl="api/UploadAzure/Upload"></UploaderAsyncSettings>
</SfUploader>
```

**Step 7:** Finally, execute the project, select the files, and upload them.

![Execute the project, select and upload the files](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Execute-the-project-select-and-upload-the-files.png)Thus, we have uploaded our files in Azure Blob Storage in a Blazor WebAssembly application. Refer to the following screenshot.

![Azure Blob Storage account displaying the uploaded file](https://www.syncfusion.com/blogs/wp-content/uploads/2021/11/Azure-Blob-Storage-account-displaying-the-uploaded-file.png)

## GitHub reference

For more details, refer to the [Upload files to Azure Blob storage using the Blazor File Upload demo](https://github.com/SyncfusionExamples/upload-files-to-azure-using-blazor-file-upload/ "Link to Upload files to Azure using Blazor file upload demo on GitHub").

## Conclusion

Thanks for reading! In this blog, we have seen the simple procedures to upload Blazor files in the Azure Blob Storage using the Syncfusion [Blazor File Upload](https://www.syncfusion.com/blazor-components/blazor-file-upload "Link to Blazor File Upload component") component. With this, you can easily store your huge amount of files in the cloud and access them anywhere and anytime. Try out the steps here and leave your feedback in the comments section below!

[Syncfusion Essential Studio for Blazor](https://www.syncfusion.com/blazor-components "Link to Blazor UI components") offers over 70 high-performance, lightweight, and responsive UI components for the web, including file-format libraries, in a single package. Use them to build stunning web applications!

You can also contact us through our [support forum](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [Direct-Trac](https://www.syncfusion.com/support/directtrac/ "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/blazor-components "Link to Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Synchronize Blazor Resource Scheduler with RESTful Services](https://dev.to/syncfusion/easily-synchronize-blazor-resource-scheduler-with-restful-services-3gj3 "Link to Easily Synchronize Blazor Resource Scheduler with RESTful Services blog")
- [Steps to Synchronize JIRA Calendar Tasks with the Blazor Scheduler](https://dev.to/karthickramasamy08/easy-steps-to-synchronize-jira-calendar-tasks-with-the-blazor-scheduler-59ff-temp-slug-1504815 "Link to Easy Steps to Synchronize JIRA Calendar Tasks with the Blazor Scheduler blog")
- [Import and Export RTF Files in Blazor with Accuracy](https://dev.to/syncfusion/easily-import-and-export-rtf-files-in-blazor-with-accuracy-1gf "Link to Easily Import and Export RTF Files in Blazor with Accuracy blog")
- [Elegantly Visualize Data with the World’s Fastest Blazor Charts](https://dev.to/kartik110895/elegantly-visualize-data-with-the-worlds-fastest-blazor-charts-40m1-temp-slug-5015072 "Link to Elegantly Visualize Data with the World’s Fastest Blazor Charts blog")