How to pass custom data to the client on Blazor file upload

Query: How to pass custom data to the client on Blazor file upload

Answer:
While hosted in Azure, some additional responses will be added in the header for security and cross-browser compatibility. Please find the Microsoft documentation to know more about this.   
   
MSDN Link: https://docs.microsoft.com/en-us/azure/api-management/api-management-cross-domain-policies  

When we passed the additional parameter to the Uploader component from the controller, we can get that value by finding among all the headers which is available in the response. And this will not change whether it will hosted in azure or local. Kindly refer the below code example.  

[SampleDataController.cs 

        [HttpPost("[action]")]  

        public void Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles)  

        {  

            long size = 0;  

            try  

            {  

                foreach (var file in UploadFiles)  

                {  

                    var filename = ContentDispositionHeaderValue  

                            .Parse(file.ContentDisposition)  

                            .FileName  

                            .Trim('"');  

                    var folders = filename.Split('/');  

                    var uploaderFilePath = hostingEnv.ContentRootPath;  

                    // for Directory upload  

                    if (folders.Length > 1)  

                    {  

                        for (var i = 0; i < folders.Length - 1; i++)  

                        {  

                            var newFolder = uploaderFilePath + $@"\{folders[i]}";  

                            Directory.CreateDirectory(newFolder);  

                            uploaderFilePath = newFolder;  

                            filename = folders[i + 1];  

                        }  

                    }  

                    filename = uploaderFilePath + $@"\{filename}";  

                    size += file.Length;  

                    if (!System.IO.File.Exists(filename))  

                    {  

                        using (FileStream fs = System.IO.File.Create(filename))  

                        {  

                            file.CopyTo(fs);  

                            fs.Flush();  

                        }  

  

                    }  

                }  

            }  

            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;  

            }  

            Response.Headers.Add("ID""Failure");  

        }  

[index.razor 

@using Syncfusion.Blazor.Inputs  

  

<SfUploader ID="UploadFiles" AutoUpload="false">  

    <UploaderAsyncSettings SaveUrl="api/SampleData/Save" RemoveUrl="api/SampleData/Remove"></UploaderAsyncSettings>  

    <UploaderEvents Success="OnSuccess"></UploaderEvents>  

</SfUploader>  

<p>key value is: @key</p>  

<p>pair value is: @value</p>  

@code  

{  

      

    public string customHeader { getset; } = "";  

    public string key { getset; } = "";  

    public string value { getset; } = "";  

  

    public void OnSuccess(Syncfusion.Blazor.Inputs.SuccessEventArgs args)  

    {  

        var customHeader = new string[] { };  

        customHeader = args.Response.Headers.Split(new Char[] { '\n' }); // To split the response header values  

        for (var i =0; i< customHeader.Length; i++)  

        {  

            if(customHeader[i].Split(new Char[] { ':' })[0]  == "id")  

            {  

                key = customHeader[i].Split(new Char[] { ':' })[0]; // To get the key pair of provided custom data in header  

                value = customHeader[i].Split(new Char[] { ':' })[1].Trim(); // To get the value for the key pair of provided custom data in header  

            }  

        }  

  

    }  

}  


Find the sample for pass custom data to client on Blazor file upload from here.

16 Replies 1 reply marked as answer

DO DotCom April 16, 2021 06:46 AM UTC

This solution is no longer working, at least in version 19.1.0.56, because Syncfusion.Blazor.Inputs.SuccessEventArgs.Response.Headers only contains the Content-Length and the Content-Type headers. Example:

"content-length: 381\r\ncontent-type: application/json; charset=utf-8\r\n"

No matter how the custom headers are formatted, they are never available in the Success event.
Is there any other solution? We need tu pass custom data to the client with the file upload response, reimplementing the whole upload workflow just for this problem would be painful.


BC Berly Christopher Syncfusion Team April 19, 2021 09:06 AM UTC

Hi DotCom, 
 
Greetings from Syncfusion support. 

We have checked the shared sample in the latest version 19.1.0.56 and the response header was added properly and available under the success event arguments. So, we have taken video demonstration and attached it below. 

 
 
So, please check the attached sample and video, and share the details whether you have faced this issue in server-side or client-side Blazor application and application framework details that will help us to check and proceed further from our end. 

Regards, 
Berly B.C

Marked as answer

DO DotCom May 13, 2021 08:02 AM UTC

Thanks for the support, we tried the sample project and it works correctly, even if we change the target to net5.0.

We didn't find any relevant difference between the sample and our project (which uses server-side Blazor and targets .NEt 5.0). 

Here is the Blazor component:

<SfUploader AllowedExtensions=".xlsx"
            AllowMultiple="false"
            Enabled="@(context.Operation== null)">
    <UploaderAsyncSettings SaveUrl="@($"{ClientBackend.PublicUrl}/api/v1/FileMge")" />
    <UploaderEvents FileSelected="UploaderFileSelect"
                    Success="UploaderSuccess" />
</SfUploader>

And these are the event methods:

protected void UploaderFileSelect(SelectedEventArgs args)
{
    // Adds authentication
    args.CurrentRequest = new List<object> { new { Authorization = Auth.GetToken() } };
}

protected async void UploaderSuccess(SuccessEventArgs args)
{
    Console.WriteLine(args.Response.Headers);
}

In the UploaderSuccess method, args.Response.Headers always contains only the Content-Length and the Content-Type headers.


JM Jeyanth Muthu Pratheeban Sankara Subramanian Syncfusion Team May 14, 2021 12:42 PM UTC

Hi DotCom, 

Thanks for the update. 

We checked the provided code snippets. On examining the provided code, you are sending authorizing token with the help of Selected event and obtaining the header information from the server using Success event. We would like to let you know that we can add the additional data to the server using Selected event and we can receive the same in the server. And we can add the header information in the server and receive the same in the Success event. Also, we could not reproduce the reported issue in our end. So kindly share the issue reproducible sample to validate your query further in our end. 

Regards, 
Jeyanth. 



XA Xavier January 14, 2022 08:53 AM UTC

Hi support.


I'm in the same situation as DotCom is. Or even worst. My 'arg.Response.Headers' where fine in 'onSuccess' one week ago!.

Then, suddently 'arg.Response.Headers' is just showing a "content type 0\r\n" string.


- Nothing has changed in my code since.

- Your example works fine, even with .NET 6 and Syncfusion 19.4.0.38, with IIS and Kestrel, all combinations.

- When I upload a file, I can see the right response headers in Chrome > console > network.


is there anything that I should consider in my program.cs or elsewere that I'm doing wrong? Has DotCom succeded with this?


Thank you so much.



PM Ponmani Murugaiyan Syncfusion Team January 17, 2022 12:13 PM UTC

Hi Xavier, 

The attached sample working as expected in our end till the latest version. So, we request you to share the issue reproducing sample to check and provide you the solution at earliest. 


Regards, 
Ponmani M 



XA Xavier January 18, 2022 08:07 AM UTC

Hi again.


I've prepared the sample for you. There is an index page with a browser. Just upload the file.

There are 2 points of interest, both with the comment "FOR SYNCFUSION" in the code.


1. The controller that adds the header on upload.

2. Your SFUpload onSuccess method that receives the header.


The header appears to be empty.


- I've removed all authentication to make this simple and clean.

- I've added a password in the zip file (as there is some third party licensed html inside). Please, tell me where to send this password.

- Please, start both projects with 'multiple project startup'


Thank you for your support.


Attachment: Parlam.Events_978df9ee.zip


PM Ponmani Murugaiyan Syncfusion Team January 19, 2022 04:46 PM UTC

Hi Xavier, 

Currently we are checking your reported query, will update further details in 2 business days (January 21, 2022). 

Regards, 
Ponmani M 



XA Xavier January 20, 2022 07:14 AM UTC

Hi Ponmani.


You will need me to send you a password for the ZIP file. Would you send me instructions?


Thank you.



PM Ponmani Murugaiyan Syncfusion Team January 24, 2022 02:58 AM UTC

Hi Xavier,  

Currently we are checking your reported query, we need additional time to investigate further, will update further details in 2 business days. 

Regards,  
Ponmani M 



XA Xavier January 31, 2022 11:15 AM UTC

Hi Ponmani.

Do you have any news about this issue?

Thank you

Xavi.



PM Ponmani Murugaiyan Syncfusion Team February 1, 2022 11:36 AM UTC

Hi Xavier,   

Based on further investigation on the above mentioned issue, we would like to know you that in the blazor WASM application, there is no need to use cookies for authentication. So browser cross origins, headers are removed, and the response headers are not returned in the success event. As a result, we recommend calling the AllowCredentials() method, as shown in the code snippet below, to allow header configuration in the startup page. 

[WebAPI/Startup.cs ] 

services.AddCors(options =>  
            {  
                options.AddDefaultPolicy(  
                    builder =>  
                    {     
                    builder.WithOrigins("https://localhost:5001")  
                           .AllowAnyMethod()  
                           .AllowAnyHeader()  
                           .AllowCredentials()  
                           .WithExposedHeaders("*");  
            });  
});  


Regards, 
Ponmani M 



XA Xavier February 1, 2022 06:57 PM UTC

Ponmani.


It worked! This was the solution "WithExposedHeaders("*")", no need to allow credentials.


Thank you for your great support!



PM Ponmani Murugaiyan Syncfusion Team February 2, 2022 07:37 AM UTC

Hi Xavier,    

Welcome, we are glad to hear that the issue has been resolved in your end. 

Regards, 
Ponmani M 



VA Vlad Andronache April 5, 2024 05:41 AM UTC

Hey,


Is there an update on this ? 

Is this still the recommended way of sending a response to the client ? I am surprised there is not an elegant way of simply returning JSON in the body. 


Thank you



YS Yohapuja Selvakumaran Syncfusion Team April 9, 2024 01:54 PM UTC

Hi Vlad Andronache,


We would like to inform you that you can retrieve custom headers from the server to the client using the above approach provided in this forum. For further information on passing custom headers from the server to the client, please refer to the following forum.


Forum: https://www.syncfusion.com/forums/153677/get-response-when-upload-file



We have already considered this request Provide support for catch the returned response body in uploader componentas feature from our end and the this will be implemented with our upcoming Volume 2 main release which is expected to be scheduled on June 28th, 2024.


You can track the status of this report through the following feedback link,


Feedback link: https://www.syncfusion.com/feedback/42492/need-to-provide-support-to-display-the-selected-items-as-chips-when-using



Regards,

Yohapuja S


Loader.
Up arrow icon