We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

Struggling to upload image to azure blob

Thread ID:

Created:

Updated:

Platform:

Replies:

149385 Nov 24,2019 08:52 PM UTC Sep 17,2020 01:49 PM UTC Blazor 8
loading
Tags: File Upload
Rhys Gordon
Asked On November 24, 2019 08:52 PM UTC

Hello,

I am trying to get the file upload component to pass an image file to a separate ASP.NET Core Web API, which will upload this file to azure blob storage. 
But the file fails to upload every time. 

Could some one please help me with this, when uploading the Uploader never even hits the API? If there is a better way to do it please let me know.

Also, is the file upload tool able to be configured to receive the URL as a response back from the API after the file as been uploaded?

I give the API end point to the file upload tool.

                        <div style="margin-top: 15px;">
                            <EjsUploader AutoUpload="true" Multiple="false" ID="UploadFiles" @ref="uploader">
                                <UploaderAsyncSettings SaveUrl="https://example/api/upload/save"></UploaderAsyncSettings>
                            </EjsUploader>
                        </div>


The below is in the Web API.

        [HttpPost("[action]")]
        public void Save(IList<IFormFile> UploadFiles)
        {
            try
            {
                foreach (var file in UploadFiles)
                {

                    const string accountName = "exampleaccount";
                    const string key = "examplekey";

                    var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);

                    var blobClient = storageAccount.CreateCloudBlobClient();
                    var container = blobClient.GetContainerReference("images");
                    await container.CreateIfNotExistsAsync();
                    await container.SetPermissionsAsync(new BlobContainerPermissions()
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });

                    var blob = container.GetBlockBlobReference("test.jpg");
                    using (var stream = file.OpenReadStream())
                    {
                        await blob.UploadFromStreamAsync(stream);
                    }

                }
            }
            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;
            }
        }

Saranya Dhayalan [Syncfusion]
Replied On November 25, 2019 01:13 PM UTC

Hi Rhys, 
 
Thank you for contacting Syncfusion support, 
 
We have checked your reported issue cause of the issue is the uploader save action configration in server-side blazor application, using MVC via UseMvcWithDefaultRoute in ASP.NET Core 3.0 and services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0) on IServiceCollection requires an explicit opt-in inside Startup.cs page. Please find the below documentation link: 
 
 
Please find the below code snippet: 
 
SampleDatacontroller.cs 
using Microsoft.AspNetCore.Hosting; 
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 BlazorApp1.Data 
{ 
    [Route("api/[controller]")] 
    public class SampleDataController : Controller 
    { 
        private IHostingEnvironment hostingEnv; 
        public IActionResult Index() 
        { 
            return View(); 
        } 
 
        public SampleDataController(IHostingEnvironment env) 
        { 
            this.hostingEnv = env; 
        } 
 
         
        [HttpPost("[action]")] 
        public async void Save(IList<IFormFile> UploadFiles) 
        { 
            try 
            { 
                foreach (var file in UploadFiles) 
                { 
 
                    const string accountName = "exampleaccount"; 
                    const string key = "examplekey"; 
 
                    var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true); 
 
                    var blobClient = storageAccount.CreateCloudBlobClient(); 
                    var container = blobClient.GetContainerReference("images"); 
                    await container.CreateIfNotExistsAsync(); 
                    await container.SetPermissionsAsync(new BlobContainerPermissions() 
                    { 
                        PublicAccess = BlobContainerPublicAccessType.Blob 
                    }); 
 
                    var blob = container.GetBlockBlobReference("test.jpg"); 
                    using (var stream = file.OpenReadStream()) 
                    { 
                        await blob.UploadFromStreamAsync(stream); 
                    } 
 
                } 
            } 
            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; 
            } 
        } 
 
    } 
 
    
} 
 
 
Please find the below screens shot for uploader hits the web API 
 
 
 
 
For your convenience we have prepared a sample. please find the below sample link: 
 
 
 
Could you please check the above sample and get back to us if you need further assistance on this? 
 
Regards, 
Saranya D 


Rhys Gordon
Replied On November 29, 2019 10:43 PM UTC

Thank you! That's exactly what I was missing.

Saranya Dhayalan [Syncfusion]
Replied On December 2, 2019 08:36 AM UTC

Hi Rhys 
 
Most Welcome.  
 
Please let us know, if you need any further assistance on this.  
 
Regards, 
Saranya D 


Wei
Replied On January 22, 2020 03:54 AM UTC

Can I trunk upload large file (let's say 100MB file) to Azure Blob? If so, can you please post a sample?

Thanks
Wei

Jeyanth Muthu Pratheeban Sankara Subramanian [Syncfusion]
Replied On January 23, 2020 03:00 PM UTC

Hi Wei,


Thanks for your update.

 

We have validated your reported scenario for large file upload to Azure storage. By default, Azure file storage not merge the file to same location and multiple chunk file stream. We suggest to use session for  save the chunk file. Once complete all chunk file, you can get the session based on session key and save to Azure location. We have achieved your scenario for save the chunk file to Azure location. Please find the code snippet and sample for your reference.

 

Save.cs

 

 

       [HttpPost]

        [Route("Save")]

        public async Task Save(IList<IFormFile> chunkFile)

        {

            try

            {

                foreach (var file in chunkFile)

                {

                    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();

                            var content = new byte[] { };

                            if (HttpContext.Session.Get("streamFile") != null)

                            {

                                content = HttpContext.Session.Get("streamFile").Concat(byteArr).ToArray();

                            } else

                            {

                                content = byteArr;

                            }

                            HttpContext.Session.Set("streamFile", content);

                        }

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

                        {

                            var fileArray = HttpContext.Session.Get("streamFile");

                            var storageCredentials = new StorageCredentials("<AccName>", "<AccKey>");

                            var cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);

                            var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

                            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 < fileArray.Length; i++)

                                {

                                    fileStreams.WriteByte(fileArray[i]);

                                }

                                fileStreams.Seek(0, SeekOrigin.Begin);

                                HttpContext.Session.Remove("streamFile");

                                await blockBlob.UploadFromStreamAsync(fileStreams);

                            }

                        }

                    }

                }

            }

            catch (Exception e)

            {

                . . .

            }

        }

 

Startup.cs

 

public void ConfigureServices(IServiceCollection services)

        {

         . . .    

 

           services.AddSession(options => {

                options.IdleTimeout = TimeSpan.FromMinutes(30);

            });

. . .

        }

 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

        {

. . .

 

   app.UseSession();

 

. . .

}

 

 

Sample Link:  https://www.syncfusion.com/downloads/support/directtrac/general/ze/BlazorApp1-1448603423


Regards,

Jeyanth.


Wei
Replied On January 27, 2020 03:27 AM UTC

Thanks Jeyanth, however, maybe i am from old school, bit i am not quite convinced that storing big size of stream data into session is good practice (In my design, my web api has to think of scale up in the future, if use session, i may have to use SQL session, which is not my favor solution). I am looking at following post, hope I could find a better way from there.


Thanks
Wei


Sureshkumar P [Syncfusion]
Replied On January 27, 2020 07:04 AM UTC

Hi Wei, 
 
 
Regards, 
Sureshkumar P 


David Adler
Replied On September 17, 2020 01:49 PM UTC

Wei,

Were you able to solve this issue of being able to upload large files to Azure Blob storage without using a session?

Thanks,

Dave


CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

Please sign in to access our forum

This page will automatically be redirected to the sign-in page in 10 seconds.

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon