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. Image for the cookie policy date

Struggling to upload image to azure blob

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

8 Replies

SD Saranya Dhayalan Syncfusion Team 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 



RG Rhys Gordon November 29, 2019 10:43 PM UTC

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


SD Saranya Dhayalan Syncfusion Team 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 



WE Wei 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


JM Jeyanth Muthu Pratheeban Sankara Subramanian Syncfusion Team 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.



WE Wei 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



SP Sureshkumar P Syncfusion Team January 27, 2020 07:04 AM UTC

Hi Wei, 
 
 
Regards, 
Sureshkumar P 



DA David Adler 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


Loader.
Live Chat Icon For mobile
Up arrow icon