Windows Azure Storage SDK

Need to download and install the Windows Azure Storage SDK first.

Go to NuGet Package Manager and search for “WindowsAzure.Storage”

Note: There is a new version of SDK “Azure.Storage.Blobs” but not all functions has been migrated over to the newer version.

Example:

Index.razor

Note: The ID field must be “UploadFiles” to match the “IList UploadFiles” in the controller, else UploadFiles in the controller will always be null.

    <SfUploader ID="UploadFiles" AutoUpload="true" Multiple="false"  MaxFileSize="104857600">
        <UploaderAsyncSettings SaveUrl="api/SampleData/Save" ChunkSize="500000"></UploaderAsyncSettings>
    </SfUploader>

The sample is configured with maximum file size as “100 MB” to upload. (1024 x 1024 x 100 = 104,857,600)

SampleDataController.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;

namespace CoreHostedFileUpload.Server.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SampleDataController : ControllerBase
    {
        public static byte[] content = new byte[] { }; 
        [HttpPost("[action]")]
        public async Task Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles)
        {
            try

            {
                const string accountName = "****"; // Provide the account name
                const string key = "****"; // Provide the account key

                var storageCredentials = new StorageCredentials(accountName, key);

                var cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);

                var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

                var isChunkFile = false;
              

                foreach (var file in chunkFile)

                {

                    isChunkFile = true;

                    var httpPostedChunkFile = HttpContext.Request.Form.Files["chunkFile"];

                    var chunkIndex = HttpContext.Request.Form["chunk-index"];

                    var totalChunk = HttpContext.Request.Form["total-chunk"];

                    using (var fileStream = file.OpenReadStream())

                    {

                        if (Convert.ToInt32(chunkIndex) <= Convert.ToInt32(totalChunk))

                        {

                            var streamReader = new MemoryStream();

                            fileStream.CopyTo(streamReader);

                            var byteArr = streamReader.ToArray();

                            if(content.Length > 0)
                            {
                                content =  content.Concat(byteArr).ToArray();
                            }
                            else
                            {
                                content = byteArr;
                            }

                        }

                        if (Convert.ToInt32(chunkIndex) == Convert.ToInt32(totalChunk) - 1)

                        {
                            

                            var container = cloudBlobClient.GetContainerReference("filo");

                            CloudBlockBlob blockBlob = container.GetBlockBlobReference(httpPostedChunkFile.FileName);

                            using (FileStream fileStreams = new FileStream(httpPostedChunkFile.FileName, FileMode.Create))

                            {

                                for (int i = 0; i < content.Length; i++)

                                {

                                    fileStreams.WriteByte(content[i]);

                                }

                                fileStreams.Seek(0, SeekOrigin.Begin);

                                content = new byte[] { };

                                await blockBlob.UploadFromStreamAsync(fileStreams);

                            }

                        }

                    }

                }

                if(UploadFiles != null && !isChunkFile)
                {
                    foreach (var file in UploadFiles)
                    {

                        var container = cloudBlobClient.GetContainerReference("filo");
                        await container.CreateIfNotExistsAsync();
                        await container.SetPermissionsAsync(new BlobContainerPermissions()
                        {
                            PublicAccess = BlobContainerPublicAccessType.Blob
                        });

                        var httpPostedFile = HttpContext.Request.Form.Files["UploadFiles"];

                        var blob = container.GetBlockBlobReference(httpPostedFile.FileName);
                        using (var stream = file.OpenReadStream())
                        {
                            await blob.UploadFromStreamAsync(stream);
                        }

                    }
                }

            }

            catch (Exception e)

            {
                content = new byte[] { };
                Response.Clear();
                Response.StatusCode = 204;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;

            }
        }
    }
}

Example 2:

Index.razor

            <SfUploader ID="UploadFiles" AutoUpload="true" Multiple="true"  AllowedExtensions=".pdf, .doc" DropArea=".control-fluid" MaxFileSize="10485760">
                <UploaderEvents OnActionComplete="@(e => OnFileUpoadCompleted(e))"></UploaderEvents>
                <UploaderAsyncSettings SaveUrl="api/SampleData/Save?Id=123" ChunkSize="50000"></UploaderAsyncSettings>
            </SfUploader>

IndexBase.cs

        public async Task OnFileUpoadCompleted(ActionCompleteEventArgs args)
        {
            Console.WriteLine("file completed: " + args.FileData.Count);
        }

SampleDataController.cs

    [HttpPost("[action]")]
    public async Task Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles, string Id)
    {

}

Sources:

https://www.syncfusion.com/forums/160405/sfuploader-working-with-azure-storage-blobs

https://blazor.syncfusion.com/demos/file-upload/chunk-upload?theme=bootstrap4

Last modified: March 28, 2021

Author

Comments

Write a Reply or Comment