Articles in this section
Category / Section

Handling Custom Data with File Upload Component in Blazor

4 mins read

When working with file uploads in a Blazor application, you may need to send additional data from the client to the server or receive custom data from the server. The Syncfusion Blazor File Upload component provides a way to handle this scenario.

Sending Additional Data from Client to Server

To send custom form data along with the file being uploaded, you can use the BeforeUpload event. Here’s an example of how to add custom data to the request:

<SfUploader ID="UploadFiles">
    <UploaderEvents BeforeUpload="@BeforeUploadHandler" ></UploaderEvents>
</SfUploader>

private void BeforeUploadHandler(BeforeUploadEventArgs args)
{
    // Send the custom form data to the server
    args.CustomFormData = new List<object> { new { Name = "Syncfusion" } };
}

Handling the Uploaded File on the Server

On the server side, you can access the additional form data sent from the client. Here’s how you can handle the file save operation:

[HttpPost("[action]")]
public async Task<IActionResult> Save(IFormFile UploadFiles)
{
    //Receive the additional form data
    var form = Request.Form["Name"];

    // ... rest of the save logic
}

Sending Custom Data from Server to Client

After processing the file upload, you may want to send a response back to the client. You can do this by appending custom headers to the response:

public string uploads = ".\\Uploaded Files"; // replace with your directory path

[HttpPost("[action]")]
public async Task<IActionResult> Save(IFormFile UploadFiles) // Save the uploaded file here
{
    if (UploadFiles.Length > 0)
    {
        var filePath = Path.Combine(uploads, UploadFiles.FileName);
        if (System.IO.File.Exists(filePath))
        {
            //Return custom-error if file already exists
            Response.Headers.Append("custom-error", "File already exists.");

            //Return conflict status code
            return new StatusCodeResult(StatusCodes.Status409Conflict);
        }
        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            //Save the uploaded file to server
            await UploadFiles.CopyToAsync(fileStream);
        }
    }
    //Return success response
    Response.Headers.Append("success", "File saved successfully.");
    return Ok();
}

Handling Server Response on the Client

To handle the custom server response on the client, you can use the Success and OnFailure events:

<SfUploader ID="UploadFiles">
    <UploaderEvents Success="@SuccessHandler" OnFailure="@OnFailureHandler"></UploaderEvents>
</SfUploader>

private void SuccessHandler(SuccessEventArgs args)
{
    // Get the custom header value from the server
    var headersString = args.Response.Headers;
    var headers = headersString.Split(new[] { "\r\n" }, StringSplitOptions.None)
        .Where(x => !string.IsNullOrWhiteSpace(x))
        .Select(x => x.Split(new[] { ": " }, 2, StringSplitOptions.None))
        .ToDictionary(x => x[0], x => x[1]);

    // Set the custom header value to the status text
    args.StatusText = headers.ContainsKey("success") ? headers["success"] : args.StatusText;
}

private void OnFailureHandler(FailureEventArgs args)
{
    // Get the custom header value from the server
    var headersString = args.Response.Headers;
    var headers = headersString.Split(new[] { "\r\n" }, StringSplitOptions.None)
        .Where(x => !string.IsNullOrWhiteSpace(x))
        .Select(x => x.Split(new[] { ": " }, 2, StringSplitOptions.None))
        .ToDictionary(x => x[0], x => x[1]);

    // Set the custom header value to the status text
    args.StatusText = headers.ContainsKey("custom-error") ? headers["custom-error"] : args.StatusText;
}

Deleting Files on the Server

To remove a file from the server, you can use the Remove action:

[HttpPost("[action]")]
public void Remove(string UploadFiles) // Delete the uploaded file here
{
    if(UploadFiles != null)
    {
        var filePath = Path.Combine(uploads, UploadFiles);
        if (System.IO.File.Exists(filePath))
        {
            //Delete the file from server
            System.IO.File.Delete(filePath);
        }
    }
}

This guide provides a basic understanding of how to send and receive custom data with the Syncfusion Blazor File Upload component.

Sample

For a complete working example, you can refer to the provided sample project by Syncfusion:

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied