File Upload: How to pass custom header to the DocumentUpload controller when saving a file

Dear Syncfusion Team,

I would like to send a custom header parameter (string) to my upload controller, when I am saving a file. How should I add this header to the file upload request and how should I get the passed parameter in the controller?

Is there any way to achieve this with your Upload controller?

Regards,
Istvan

7 Replies 1 reply marked as answer

SN Sevvandhi Nagulan Syncfusion Team September 21, 2020 12:41 PM UTC

Hi Szöke,    
   
     
Greetings from Syncfusion support.   
     
We have validated your reported query for “How to pass custom header”. The uploader component allows you to add additional header on file upload and can be received in the server-side. You can achieve this behaviour using FileSelected / BeforeUpload event and its CurrentRequest argument by configure header as key-value pair.     
    
     
[index.razor]    
@using Syncfusion.Blazor.Inputs    
<SfUploader ID="UploadFiles">    
    <UploaderEvents FileSelected="onFileSelect"></UploaderEvents>    
    <UploaderAsyncSettings SaveUrl="api/SampleData/Save">    
    </UploaderAsyncSettings>    
</SfUploader>    
    
@code {    
    
    private void onFileSelect(SelectedEventArgs args)    
    {    
        var accessToken = "Basic test123";    
        args.CurrentRequest = new List<object> { new { Authorization = accessToken } };    
    }    
    
}    
[SampleDataController.cs]    
[HttpPost("[action]")]    
        public async void Save(IList<IFormFile> UploadFiles)    
        {    
            //to get authorization Header to handle save file on server side      
            var authorizationHeader = Request.Headers["Authorization"];    
            try    
            {    
                foreach (var file in UploadFiles)    
                {    
                    if (UploadFiles != null)    
                    {    
                        var filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');    
                        filename = hostingEnv.WebRootPath + $@"\{filename}";    
                        if (!System.IO.File.Exists(filename))    
                        {    
                            using (FileStream fs = System.IO.File.Create(filename))    
                            {    
                                file.CopyTo(fs);    
                                fs.Flush();    
                            }    
                        }    
                        else    
                        {    
                            Response.Clear();    
                            Response.StatusCode = 204;    
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File already exists.";    
                        }    
                    }    
                }    
                Response.Headers.Add("ID""Failure"); // Assign the custom data in the response header.    
            }    
            catch (Exception e)    
            {    
                Response.Clear();    
                Response.ContentType = "application/json; charset=utf-8";    
                Response.StatusCode = 204;    
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";    
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;    
            }    
                
        }    
 
     
   
Screenshot:    
   
   
     
   
   
Please find the sample from the below link.    

     
     
Regards,    
Sevvandhi N   


Marked as answer

SI Szöke Istvan September 22, 2020 06:58 AM UTC

Hi Sevvandhi,

Thanks for your help.

Regards,
Istvan


SN Sevvandhi Nagulan Syncfusion Team September 23, 2020 05:07 AM UTC

Hi Szöke, 


Thanks for the update. Please let us know if you need further assistance. 


Regards, 
Sevvandhi N 



OR Otoo Rashid N A June 30, 2022 12:58 PM UTC

I have the same thing produced in angular with the 'CurrentRequest' in both 'FileSelected / BeforeUpload' but the 'header' is not added when the request is made to the server


Attachment: Uploader_CurrentRequest_20220630_125439_ad8c5b05.zip


UD UdhayaKumar Duraisamy Syncfusion Team July 2, 2022 07:01 AM UTC

Hi Otoo,


We checked the reported query. We can add the extra parameter to the SaveURL using the uploading event which triggers when the file is being uploaded. In that event, we can add the additional data in the key-value pair with the help of customFormData property in the Uploading event args. We can receive the added data in the server end by accessing the key value. 


public onFileUpload = (argsany=> {

    // add addition data as key-value pair.

    const auth = 'Syncfusion INC';

    args.customFormData = [{ Authorization: auth }];

  };


// Get the additional data in server end by corresponding key. 

    var data = HttpContext.Current.Request.Form["Authorization "]; 


Screenshot Reference:


Please find the sample and UG in the below link.


Sample : https://stackblitz.com/edit/angular-nkujjt-fexmep?file=app.component.ts,app.component.html


UG Link : https://ej2.syncfusion.com/angular/documentation/uploader/how-to/add-additional-data-on-upload/


Please let us know if you need any further assistance on this.


Regards,

Udhaya Kumar D




JV Jeff Voigt May 26, 2023 01:48 PM UTC

We need to be able to do this in react without the form data but with actual headers in the request for consistency and adherence to the https protocol standards.  We need to pass in additional "HEADERS" for the "Bearer" and NOT form data.  How can this be acehived?



UD UdhayaKumar Duraisamy Syncfusion Team June 4, 2023 05:24 AM UTC

If you need to pass additional headers for the "Bearer" token without using form data, you can modify the code as follows:


const onFileUpload = async (args=> {

    const auth = 'Syncfusion INC';

    const formData = new FormData();

    formData.append('file'args.file);

 

    try {

      const response = await fetch(asyncSettings.saveUrl, {

        method: 'POST',

        headers: {

          Authorization: `Bearer ${auth}`,

        },

        body: formData,

      });

 

      if (response.ok) {

        // Handle success

        alert('success');

      } else {

        // Handle error

        alert('Unsuccess');

      }

    } catch (error) {

      // Handle error

      console.log(error);

    }

  };

 


In this code, the fetch API is used to make the POST request with the file upload. The request is configured with the appropriate method, headers, and body (using formData). The response is then checked for its status using response.ok, and you can handle success or error accordingly.



Sample: https://stackblitz.com/edit/react-xkmhru?file=index.js


Loader.
Up arrow icon