Simple Steps to Upload Files to Azure Blob Storage in Blazor App
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (175).NET Core  (29).NET MAUI  (208)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (220)BoldSign  (15)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (67)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (101)Streamlit  (1)Succinctly series  (131)Syncfusion  (920)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (37)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (151)Chart  (132)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (633)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (41)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (508)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (597)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Simple Steps to Upload Blazor Files to Azure Blob Storage

Simple Steps to Upload Files to Azure Blob Storage in Blazor App

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 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 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:

Prerequisites

Creating Azure storage

First, sign in to the Azure portal to create a storage account. If you don’t have a subscription, create a free subscription account and follow these steps:

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

Select the Storage accounts optionStep 2: Then, on the Storage accounts page, select Create.

On the Storage accounts page, select CreateOptions for your new storage account will be listed on the Create a storage account page.

Create a storage account page

Syncfusion’s Blazor components suite is the expert’s choice for building modern web apps.

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

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 successfully

Note: For more details about the options in the other tabs, refer to Create a storage account documentation.

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 deploymentStep 6: After successful deployment, click Go to resource to see your storage.

Click on the Go to resource optionNow, your storage will look like the following screenshot.

Created Storage AccountStep 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.

Everything a developer needs to know to use Blazor components in the Blazor app is completely documented.

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. 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 documentation.

The following code renders the Blazor File Upload component.

<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 fileYou 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.Step 2:  Then, install the Azure.Storage.Blob library to work with the Azure Storage Blob service.

Install the Azure.Storage.Blob libraryStep 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.

[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.

[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.

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

Explore the different application UIs developed using Syncfusion Blazor components.

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

Execute the project, select and upload the filesThus, 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

GitHub reference

For more details, refer to the Upload files to Azure Blob storage using the Blazor File Upload demo.

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 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 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 forumDirect-Trac, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Comments (3)

How would this be achieved in Blazor Server ?
Thanks!

I have followed this tutorial and I get an error “failed to upload” when testing, are there any specific settings I need to set on my storage account for this to work?

When I download you project and run it in Visual Studio 2022 I only get a blank page.
If I set the client project to startup project I get errors.
How to get it to run?
Could it be blazor related?

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed