Upload Files to a Cloud Storage
- 2 minutes to read
The DevExpress Blazor Upload component allows you to upload files to a web server or cloud storage. Follow the steps below to configure your Blazor application to upload files to Microsoft Azure:
Create a storage account on Azure. Refer to Microsoft documentation for instructions: Create a storage account.
Specify the Azure connection string in the appsettings.json file as follows:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "ConnectionStrings": { "AzureConnectionString": "your-azure-connection-string" }, ... }
Open Package Manager in Visual Studio (Tools → NuGet Package Manager → Manage Packages for Solution…). In the invoked widow, install the Azure.Storage.Blobs package.
Create an Upload Controller as described in the following section: Create an Upload Controller on the Server.
In the controller class, obtain the Azure connection string and assign it to a variable as follows:
using Microsoft.AspNetCore.Mvc; namespace Cloud.Controllers { [Route("api/[controller]")] [ApiController] public class UploadController : ControllerBase { private readonly string azureConnectionString; public UploadController(IConfiguration configuration) { azureConnectionString = configuration.GetConnectionString("AzureConnectionString"); } } }
Implement a controller action that uploads a file to the Azure Blob storage:
using Azure.Storage.Blobs.Models; using Azure.Storage.Blobs; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; namespace BlazorDemo.AspNetCoreHost; [Route("api/[controller]")] [ApiController] public class UploadController : ControllerBase { [HttpPost("[action]")] public async Task Upload(IFormFile myCloudStorage) { try { // Write code that saves the 'myCloudStorage' file to the Azure Blob storage. // Don't rely on or trust the FileName property without validation. } catch(Exception e) { // Handle upload exceptions here } } }
Important
To introduce secure file upload operations to your web app, we recommend that you add different validation types to upload controller code. Refer to the following sources for more information:
Add a DxUpload component to your Blazor application’s markup. Specify UploadUrl and Name properties. The
Name
property value must match theUpload
action’s parameter name.<DxUpload Name="myCloudStorage" UploadUrl=@GetUploadUrl("api/Upload/Upload/") /> @code { protected string GetUploadUrl(string url) { return NavigationManager.ToAbsoluteUri(url).AbsoluteUri; } }
Run the application. You can now upload a file:
Once complete, the upload-container and uploaded file is shown in your Azue Blob storage: