File Upload Server Control Authentication with X-ApiKey from Header

Hello,


I have file upload control with uploadSave and FileRemove properties as decribed in documentation. But I use MVC withouot blazor on server side. I need to add extra authentication for those controls so I addded X-ApiKey auhentication on header level. I want to ask how can I add the key to header with SaveUrl and RemoveUrl in control.


Could you please help me?


1 Reply

YS Yohapuja Selvakumaran Syncfusion Team August 24, 2023 10:54 AM UTC

Hi N Ozer Senol,


Thank you for reaching out us. To achieve this, you can pass the header and the token in the Before upload event, which will then be received in the save method. We've created a sample that aligns with your requirement. For a more comprehensive understanding, We recommend referring to the sample provided in the attachment.


CodeSnippet:

[Index.razor]


@using Syncfusion.Blazor.Inputs

 

<SfUploader ID="UploadFiles">

    <UploaderEvents BeforeUpload="OnBeforeUpload"></UploaderEvents>

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

</SfUploader>

@code {

 

 

    private void OnBeforeUpload(BeforeUploadEventArgs args)

    {

        args.CustomFormData = new List<object> { new { Name = "Syncfusion" } };

        var accessToken = "Basic test123";

        args.CurrentRequest = new List<object> { new { Authorization = accessToken } };

    }

   

}


[SampleDataController.cs]


public void Save(IList<IFormFile> UploadFiles)

        {

            var auth = Request.Headers["Authorization"];

            var header = HttpContext.Request.Form["Name"];

            try

            {

                foreach (var file in UploadFiles)

                {

                    var filename = hostingEnv.ContentRootPath + $@"\{file.FileName}";

                    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;

            }

        }


We hope this sample meets your requirement. Please get back to us if you need any further assistance.


Regards,

Yohapuja S


Attachment: FileUpload_token_c7b1896b.zip

Loader.
Up arrow icon