Is it possible to send custom headers to backend when the file is removed?
Hello Syncfusion Support Team,
I have been using the UploadFile component to upload images for different entities in my Blazor project. Within the project, I want to be able to send custom headers to the Backend Controller. So far I have been able to send the headers over to the Backend when uploading a file. However, I cannot seem to get custom headers over to the Backend when removing a file that has been uploaded. Whenever I try to send them via a OnRemove event I get null responses in the Backend.
What I currently have for my razor component:
<SfUploader ID="UploadFiles" AutoUpload="true" AllowedExtensions=".jpg,.jpeg,.png,.gif,.svg" EnableHtmlSanitizer="true">
<UploaderAsyncSettings SaveUrl="@savePath" RemoveUrl="@removePath"></UploaderAsyncSettings>
<UploaderEvents FileSelected="@OnFileSelected" OnRemove="@OnFileRemove" ValueChange="@OnChange" Success="@OnSuccess"></UploaderEvents>
</SfUploader>
private async Task OnFileRemove(RemovingEventArgs args)
{
args.CurrentRequest = new List<object> { new { Authorization = "" }, new { containerName = containerName },
new { blobDirectory = productSlug + "/" + formatHash + "/cover-image"} };
}
What I have for the Backend controller:
[HttpPost("DeleteFile")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> DeleteFile([FromForm] IList<IFormFile> UploadFiles)
{
try
{
if (UploadFiles == null || UploadFiles.Count == 0)
return BadRequest("No files provided to delete.");
var storageString = _configuration.GetValue<string>("ConnectionStrings:storageConnection");
if (storageString == null)
return (IActionResult)Results.Problem(title: "Invalid connection to media storage",
statusCode: 500);
var containerName = Request.Headers["containerName"];
var blobDirectory = Request.Headers["blobDirectory"];
Console.WriteLine($" containerName = {containerName} blobDirectory = {blobDirectory}")Is there anything that I might be doing wrong when sending custom headers over to the Backend controller?
Thank you for your time and help,
Andrew
Hi Andrew,
Yes, it is absolutely possible to send custom headers to the backend when a file is removed. we've reviewed your implementation and identified the issue you were experiencing.
The problem in your code was the use of the OnRemove event. This event fires after the file removal request have already been sent to the server, which is why your custom headers were appearing as null in the backend. You need to use the BeforeRemove event instead, which fires before the HTTP request is sent, allowing you to modify the request headers.
Here's the corrected Blazor implementation:(Use BeforeRemove Event)
|
<h3>File Upload with custom headers on Remove</h3>
<SfUploader ID="UploadFiles" AutoUpload="true" AllowedExtensions=".jpg,.jpeg,.png,.gif,.svg" EnableHtmlSanitizer="true"> <UploaderAsyncSettings SaveUrl="api/upload/save" RemoveUrl="api/upload/DeleteFile" /> <UploaderEvents FileSelected="@OnFileSelected" BeforeRemove="@OnBeforeRemove" ValueChange="@OnChange" Success="@OnSuccess"></UploaderEvents> </SfUploader>
@code { private string containerName = "my-container"; private string productSlug = "product"; private string formatHash = "hash";
private Task OnFileSelected(SelectedEventArgs args) { return Task.CompletedTask; }
private Task OnChange(UploadChangeEventArgs args) { return Task.CompletedTask; }
private Task OnSuccess(SuccessEventArgs args) { Console.WriteLine($"Operation completed: {args.Response}"); return Task.CompletedTask; }
// Use BeforeRemove to add custom headers before the remove request is sent private Task OnBeforeRemove(BeforeRemoveEventArgs args) { // Add custom form data args.CustomFormData = new List<object> { new { name = "syncfusion" } };
// Add authorization header (for bearer token) var accessToken = "Authorization_token";
args.CurrentRequest = new List<object> { new { Authorization = accessToken } };
return Task.CompletedTask; } }
|
Backend Controller (Updated):
|
[[HttpPost("DeleteFile")] [Consumes("multipart/form-data")] public async Task<IActionResult> DeleteFile([FromForm] IList<IFormFile> UploadFiles) { try { if (UploadFiles == null || UploadFiles.Count == 0) return BadRequest("No files provided to delete.");
var authorization = Request.Headers["Authorization"].ToString();
Console.WriteLine($"Authorization = {authorization}");
var uploadPath = Path.Combine(hostingEnv.ContentRootPath, "wwwroot", "uploads");
foreach (var file in UploadFiles) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName? .Trim('"') ?? file.FileName;
var filePath = Path.Combine(uploadPath, filename);
if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } }
return Ok(new { message = "Files deleted successfully" }); } catch (Exception ex) { return StatusCode(500, $"Error: {ex.Message}"); } } |
Key Changes Required in Your Code:
- Replace OnRemove with BeforeRemove:
- Change: <UploaderEvents OnRemove="@OnFileRemove" />
- To: <UploaderEvents BeforeRemove="@OnBeforeRemove" />
- Update Event Handler Method:
- Change parameter type from RemovingEventArgs to BeforeRemoveEventArgs
- The header structure you had was almost correct, just needed the right event
How It Works:
- Event Timing: BeforeRemove fires before the HTTP DELETE request is made, allowing you to inject custom headers into the request
- Header Format: Each header is added as an object with name and value properties
- Backend Access: The controller receives these headers via Request.Headers["headerName"]
- Verification: Console logs confirm the headers are received correctly
This solution ensures custom headers are properly sent to your backend controller when files are removed!
As for your reference, we have included a complete sample along with a GIF demonstration showing this in action.
Gif:
Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/UploaderSampl