# Upload Events

This article describes the events of the Telerik Upload for Blazor.

First, get familiar with the [**Event Arguments**](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments) section, as it applies to all events. The [example](https://www.telerik.com/blazor-ui/documentation/components/upload/events#example) at the end also showcases all Upload events.

* [`OnCancel`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#oncancel)
* [`OnClear`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onclear)
* [`OnError`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onerror)
* [`OnPause`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onpause)
* [`OnProgress`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onprogress)
* [`OnRemove`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onremove)
* [`OnResume`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onresume)
* [`OnSelect`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onselect)
  * [Renaming uploaded files](https://www.telerik.com/blazor-ui/documentation/components/upload/events#renaming-a-file)
* [`OnSuccess`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onsuccess)
* [`OnUpload`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onupload)
  * [Sending additional custom data with the uploaded file](https://www.telerik.com/blazor-ui/documentation/components/upload/events#send-custom-data-with-the-file)

> warning Make sure to also check the section about [Upload security](https://www.telerik.com/blazor-ui/documentation/components/upload/overview#security).

> tip The event is an `EventCallback`. It can be synchronous and return `void`, or asynchronous and return `async Task`. Do not use `async void`.

## Event Arguments

The different Upload events use different event argument types, but the exposed properties are similar. Depending on the exact event, the properties will be some of these:

<style>
    .article table {
        table-layout: auto;
        word-break: normal;
    }
</style>

| Property         | Type                                                                                                                 | Description                                                                                                                                                                                                                                                                                                                                                                                     |
| ---------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Files`          | `List<UploadFileInfo>`                                                                                               | *All Upload events* expose a `Files` collection of [`UploadFileInfo`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#uploadfileinfo) members. The collection contains one or more files in the `OnClear`, `OnSelect`, and `OnUpload` handlers. The file is always one in `OnCancel`, `OnError`, `OnPause`, `OnProgress`, `OnRemove`, `OnResume`, and `OnSuccess`.     |
| `IsCancelled`    | `bool`                                                                                                               | Set to `true` to cancel the event and the respective user action.                                                                                                                                                                                                                                                                                                                               |
| `Operation`      | [`UploadOperationType`](https://www.telerik.com/blazor-ui/documentation/api/telerik.blazor.uploadoperationtype) enum | Can be `Upload` or `Remove`.                                                                                                                                                                                                                                                                                                                                                                    |
| `Progress`       | `int`                                                                                                                | The uploaded percentage of the file in the [`OnProgress` event](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onprogress).                                                                                                                                                                                                                                           |
| `Request`        | `UploadHttpRequest`                                                                                                  | Information about the server response such as status code and any custom messages. The object contains the `int` property `Status` and the `StatusText`, `ResponseType`, and `ResponseText` strings.                                                                                                                                                                                            |
| `RequestData`    | `Dictionary<string, object>`                                                                                         | Add `KeyValuePair` definitions to [send custom data](https://www.telerik.com/blazor-ui/documentation/components/upload/events#send-custom-data-with-the-file) to the controller in [`OnUpload`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onupload) and [`OnRemove`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onremove).         |
| `RequestHeaders` | `Dictionary<string, object>`                                                                                         | Add `KeyValuePair` definitions to [send custom HTTP headers](https://www.telerik.com/blazor-ui/documentation/components/upload/events#send-custom-data-with-the-file) to the controller in [`OnUpload`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onupload) and [`OnRemove`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onremove). |

> tip The custom information in `RequestData` and `RequestHeaders` can be related to authentication, CSRF cross-site anti forgery tokens, or any business logic.

### UploadFileInfo

The `UploadFileInfo` object has the following properties:

| Property             | Type                                                                                                           | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| -------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Extension`          | `string`                                                                                                       | The file extension (type), together with the dot.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `Id`                 | `string`                                                                                                       | The unique file identifier in GUID format.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `InvalidExtension`   | `bool`                                                                                                         | Defines if the file violates the [`AllowedExtensions` value](https://www.telerik.com/blazor-ui/documentation/components/upload/overview#upload-parameters).                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `InvalidMaxFileSize` | `bool`                                                                                                         | Defines if the file violates the [`MaxFileSize` value](https://www.telerik.com/blazor-ui/documentation/components/upload/overview#upload-parameters).                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `InvalidMinFileSize` | `bool`                                                                                                         | Defines if the file violates the [`MinFileSize` value](https://www.telerik.com/blazor-ui/documentation/components/upload/overview#upload-parameters).                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `Name`               | `string`                                                                                                       | The encoded file name, including the extension. One method to decode it is [`System.Net.WebUtility.HtmlDecode()`](https://learn.microsoft.com/en-us/dotnet/api/system.net.webutility.htmldecode). The file name received by the controller (endpoint) is not encoded. The [file can be renamed](https://www.telerik.com/blazor-ui/documentation/components/upload/events#renaming-a-file) in the [`OnSelect`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onselect) and [`OnUpload`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onupload) event handlers. |
| `Progress`           | `int`                                                                                                          | The uploaded percentage of the file in the [`OnProgress` event](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onprogress).                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `Size`               | `long`                                                                                                         | The file size in bytes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `Status`             | [`UploadFileStatus` enum](https://www.telerik.com/blazor-ui/documentation/api/telerik.blazor.uploadfilestatus) | The current status of the file in the context of the Upload component (`Selected`, `Uploading`, `Uploaded`, `Failed`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |

## OnCancel

The `OnCancel` event fires when the user clicks the *Cancel* icon of a file that is currently uploading.

The `UploadCancelEventArgs` event argument contains the [properties `Files` and `IsCancelled`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments). The `Files` collection contains only one file.

If you cancel the event, the upload process will continue. For example, this can depend on some [file information](https://www.telerik.com/blazor-ui/documentation/components/upload/events#uploadfileinfo) such as size and upload progress.

> caption Using the Upload OnCancel event

```RAZOR.skip-repl
<TelerikUpload OnCancel="@OnUploadCancel" />

@code {
    private void OnUploadCancel(UploadCancelEventArgs args)
    {
        var file = args.Files.First();

        if (file.Size < 2 * 1024 * 1024 && file.Progress > 50)
        {
            args.IsCancelled = true;
        }
    }
}
```

See the [full example](https://www.telerik.com/blazor-ui/documentation/components/upload/events#example) below.

## OnClear

The `OnClear` event fires when the user clicks the *Clear* button below the file list. This button is visible when [`AutoUpload="false"`](https://www.telerik.com/blazor-ui/documentation/components/upload/overview#upload-parameters).

The `UploadClearEventArgs` event argument contains the [properties `Files` and `IsCancelled`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments). The `Files` collection can contain one or more files.

If you cancel the event, the current file list will remain visible.

> caption Using the Upload OnClear event

```RAZOR.skip-repl
<TelerikUpload OnClear="@OnUploadClear" />

@code {
    private void OnUploadClear(UploadClearEventArgs args)
    {
        if (args.Files.Count > 3)
        {
            args.IsCancelled = true;
        }
    }
}
```

See the [full example](https://www.telerik.com/blazor-ui/documentation/components/upload/events#example) below.

## OnError

The `OnError` event fires when an *upload* or *remove* request fails in the controller.

The [`UploadErrorEventArgs` event argument](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments) contains the following properties:

* `Files` that contains one file
* `Operation`
* `Request`

> caption Using the OnError event with message from the controller

```RAZOR.skip-repl
<TelerikUpload OnError="@OnUploadError" />

@code {
    private void OnUploadError(UploadErrorEventArgs args)
    {
        string fileName = args.Files.First().Name;
        UploadOperationType operation = args.Operation;
        int statusCode = args.Request.Status;
        string statusMessage = args.Request.StatusText;
        string customMessage = args.Request.ResponseText;
    }
}
```

```C# Controller
[HttpPost]
public async Task<IActionResult> Save(IFormFile files)
{
    // ...
    // Different ways to return a response

    // unhandled exceptions have status code 500
    throw new Exception("Custom error message.");

    // OR

    // custom status code and error messsage
    Response.StatusCode = 400;
    await Response.WriteAsync("Custom error message.");
    return new EmptyResult();

    // OR

    // custom status code and error messsage
    Response.StatusCode = 400;
    return Content("Custom error message.");
}
```

See the [full example](https://www.telerik.com/blazor-ui/documentation/components/upload/events#example) below.

## OnPause

The `OnPause` event fires when the user clicks on the Pause button during [chunk upload](https://www.telerik.com/blazor-ui/documentation/components/upload/chunk-upload). The Pause button appears only when `UploadChunkSettings.Resumable` is `true`, which is by default.

The `UploadPauseEventArgs` event argument contains the [properties `Files` and `IsCancelled`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments). The `Files` collection contains one file.

If you cancel the event, the chunk upload will not be paused.

```RAZOR.skip-repl
<TelerikUpload OnPause="@OnUploadPause">
    <UploadSettings>
        <UploadChunkSettings Enabled="true" Resume="true" />
    </UploadSettings>
</TelerikUpload>

@code {
    private void OnUploadPause(UploadPauseEventArgs args)
    {
        string fileName = args.Files.First().Name;
    }
}
```

## OnProgress

The `OnProgress` event fires each time a file makes progress in its upload process.

The event is tied directly to the [`progress` event of the `XHR` object](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/progress_event), which sends the file to the controller. The Upload component cannot control when or how often the event will fire. For small files, the `Progress` value is likely to jump directly to `100`, especially on `localhost`.

The `UploadProgressEventArgs` event argument contains the properties [`Files` and `Progress`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments). The `Files` collection contains only one file.

> caption Using the Upload OnProgress event

```RAZOR.skip-repl
<TelerikUpload OnProgress="@OnUploadProgress" />

@code {
    private void OnUploadProgress(UploadProgressEventArgs args)
    {
        string fileName = args.Files.First().Name;
        int percentComplete = args.Progress;
    }
}
```

See the [full example](https://www.telerik.com/blazor-ui/documentation/components/upload/events#example) below.

## OnRemove

The `OnRemove` event fires when the users clicks the *Remove* (X) button of an uploaded or pending file. If the file is already uploaded, the Upload component will send a request to the server, so you can delete it. Then, the component will fire [`OnSuccess`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onsuccess) or [`OnError`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onerror).

The [`UploadEventArgs` event argument](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments) contains the following properties:

* `Files` that contains one file
* `IsCancelled`
* `RequestData` (see section [Send Custom Data with the File](https://www.telerik.com/blazor-ui/documentation/components/upload/events#send-custom-data-with-the-file))
* `RequestHeaders`

If you cancel the event, the Upload component will not send the file deletion request.

> caption Using the OnRemove event to send custom data to the controller

```RAZOR.skip-repl
<TelerikUpload OnRemove="@OnUploadRemove" />

@code {
    private async Task OnUploadRemove(UploadEventArgs args)
    {
        var file = args.Files.First();

        if (file.Extension == ".pdf")
        {
            args.IsCancelled = true;
        }
        else
        {
            args.RequestData.Add("dataKey", "dataValue");
            args.RequestHeaders.Add("headerKey", "headerValue");
        }
    }
}
```

```C# Controller
// Get the custom data and header values from additional method arguments
[HttpPost]
public async Task<IActionResult> Remove([FromForm] string files, [FromForm] string dataKey, [FromHeader] string headerKey)
{
    // ...

    string customData = dataKey;
    string customHeader = headerKey;

    // ...
}

// OR

// Get the custom data and header values from the Request object
[HttpPost]
public async Task<IActionResult> Remove([FromForm] string files)
{
    // ...

    string customData = Request.Form["dataKey"];
    string customHeader = Request.Headers["headerKey"];

    // ...
}
```

See the [full example](https://www.telerik.com/blazor-ui/documentation/components/upload/events#example) below.

## OnResume

The `OnResume` event fires when the user clicks on the Resume button during [chunk upload](https://www.telerik.com/blazor-ui/documentation/components/upload/chunk-upload). Pausing and resuming uploads requires `UploadChunkSettings.Resume` to be `true`, which is by default.

The `UploadResumeEventArgs` event argument contains the [properties `Files` and `IsCancelled`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments). The `Files` collection contains one file.

If you cancel the event, the chunk upload will not be resumed.

```RAZOR.skip-repl
<TelerikUpload OnResume="@OnUploadResume">
    <UploadSettings>
        <UploadChunkSettings Enabled="true" Resume="true" />
    </UploadSettings>
</TelerikUpload>

@code {
    private void OnUploadResume(UploadResumeEventArgs args)
    {
        string fileName = args.Files.First().Name;
    }
}
```

## OnSelect

The `OnSelect` event fires when the user selects one or more new files for upload. The selection of files is achieved either through the *Select files* button or by dropping the files anywhere in the component.

The `UploadSelectEventArgs` event argument contains the [`Files` and `IsCancelled` properties](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments). The `Files` collection can contain one or more files, and it is possible to [count the total number of selected files](https://www.telerik.com/blazor-ui/documentation/knowledge-base/upload-track-selected-uploaded-files).

If you cancel the event, the Upload component will neither list, nor upload the selected files.

### Renaming a File

In some cases, you may want to rename a selected file when uploading it, for example:

* A file with the same name already exists on the server.
* The file name does not meet some requirements.

The file rename process requires two separate steps:

1. Use the `OnSelect` event to call a remote endpoint and check for duplicates before the actual upload process starts. If needed, set a new name to the `Name` property of the file. This new name will appear in the Upload component UI. The controller will always receive `IFormFile` with the original name from the file system, due to browser security restrictions.
2. Send the new file name(s) as [additional request data](https://www.telerik.com/blazor-ui/documentation/components/upload/events#send-custom-data-with-the-file) in the [`OnUpload`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onupload) and [`OnRemove`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onremove) events. Keep in mind that `OnUpload` can fire once for multiple files, so you may have to send multiple file names to the remote endpoint. Use multiple custom key-value pairs or a single serialized `Dictionary`. Then, use the `Save` action in the remote endpoint to set the name(s) of the saved file(s).

> caption Using the Upload OnSelect event to rename files in the UI

```RAZOR.skip-repl
<TelerikUpload OnSelect="@OnUploadSelect" />

@code {
    private async Task OnUploadSelect(UploadSelectEventArgs args)
    {
        foreach (var file in args.Files)
        {
            string fileName = file.Name;
            long fileSize = file.Size;

            // Change the file name that is displayed in the TelerikUpload component.
            // Delays here will result in rendering and upload delays.
            // The IFormFile file name in the upload request will remain the original one.
            file.Name = await GetNewFileNameFromServer(file.Name, "currentUserName");
        }
    }

    private async Task<string> GetNewFileNameFromServer(string fileName, string userName)
    {
        await Task.Delay(100); // simulate network delay

        // In a real case this can be a controller action method.
        // Use the same naming logic when actually saving the file on the server.
        string newFileName = $"{userName}-{fileName}";

        return await Task.FromResult(newFileName);
    }
}
```

See the [full example](https://www.telerik.com/blazor-ui/documentation/components/upload/events#example) below.

## OnSuccess

The `OnSuccess` event fires when an upload or remove request is successful. The Upload assumes a [successful request if the `Response.StatusCode` of the controller action is between 200 and 299](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#successful_responses).

The [`UploadSuccessEventArgs` event argument](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments) contains the following properties:

* `Files` that contains one file. See [how to count the total number of uploaded files](https://www.telerik.com/blazor-ui/documentation/knowledge-base/upload-track-selected-uploaded-files).
* `Operation`
* `Request`

For example, the server can return a URL string for an image thumbnail.

> caption Using the OnSuccess event with message from the controller

```RAZOR.skip-repl
<TelerikUpload OnSuccess="@OnUploadSuccess" />

@code {
    private async Task OnUploadSuccess(UploadSuccessEventArgs args)
    {
        string fileName = args.Files.First().Name;
        UploadOperationType operation = args.Operation;
        int statusCode = args.Request.Status;
        string statusMessage = args.Request.StatusText;
        string customMessage = args.Request.ResponseText;
    }
}
```

```C# Controller
[HttpPost]
public async Task<IActionResult> Save(IFormFile files)
{
    // ...
    // Different ways to return a response

    // default status code 200, no custom success message
    return new OkResult();

    // OR

    // default status code 200 and custom success message
    return new OkObjectResult("Custom success message.");

    // OR

    // custom status code and success messsage
    Response.StatusCode = 201;
    await Response.WriteAsync("Custom success message.");
    return new EmptyResult();

    // OR

    // custom status code and success messsage
    Response.StatusCode = 201;
    return Content("Custom success message.");
}
```

See the [full example](https://www.telerik.com/blazor-ui/documentation/components/upload/events#example) below.

## OnUpload

The `OnUpload` event fires when files will be uploaded. By default, it will fire immediately after [`OnSelect`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onselect), unless `AutoUpload="false"`.

The [`UploadEventArgs` event argument](https://www.telerik.com/blazor-ui/documentation/components/upload/events#event-arguments) contains the following properties:

* `Files` that contains one or more files
* `IsCancelled`
* `RequestData`
* `RequestHeaders`

If you cancel the event, the file upload will not start. If `AutoUpload="false"`, the user will be able to try uploading the same file(s) again.

### Send Custom Data with the File

Use the `OnUpload` and [`OnRemove`](https://www.telerik.com/blazor-ui/documentation/components/upload/events#onremove) event handlers to send additional custom data and request headers to the server, together with the file. For example, the data may be related to:

* Authentication
* [CSRF/XSRF cross-site antiforgery tokens](https://www.telerik.com/blazor-ui/documentation/knowledge-base/upload-validateantiforgerytoken)
* New file name (also see section [Renaming a File](https://www.telerik.com/blazor-ui/documentation/components/upload/events#renaming-a-file))
* Any metadata related to the app business logic

To send cookies with the upload request, set the [`WithCredentials` component parameter](https://www.telerik.com/blazor-ui/documentation/components/upload/overview#upload-parameters) to `true`.

To send a complex object or a collection, serialize it first. Receive it as a `string` argument in the controller method and deserialize it.

> caption Using the OnUpload event to send custom data to the controller

<div class="skip-repl"></div>

<demo metaUrl="client/upload/events/example-1/" height="420"></demo>

```C# Controller
using System.Text.Json;

// Get the custom data and header values from additional method arguments
[HttpPost]
public async Task<IActionResult> Save(
    IFormFile files,
    [FromHeader] string headerKey,
    [FromForm] string dataKey,
    [FromForm] string collectionKey)
{
    // ...

    string customHeader = headerKey;
    string customData = dataKey;
    string[]? customCollection = JsonSerializer.Deserialize<string[]>(collectionKey);

    // ...
}

// OR

// Get the custom data and header values from the Request object
[HttpPost]
public async Task<IActionResult> Save(IFormFile files)
{
    // ...

    string? customHeader = Request.Headers["headerKey"];
    string? customData = Request.Form["dataKey"];

    if (Request.Form.ContainsKey("collectionKey"))
    {
        string[]? customCollection = JsonSerializer.Deserialize<string[]>(Request.Form["collectionKey"]!);
    }

    // ...
}
```

## Example

The `UploadController` class below assumes that the project name and namespace is `TelerikBlazorApp`.

Make sure to enable controller routing in the app startup file (`Program.cs`). In this case, the file includes the following lines:

* `builder.Services.AddControllers();`
* `app.MapDefaultControllerRoute();`

Also see:

* Section [Implement Controller Methods](https://www.telerik.com/blazor-ui/documentation/components/upload/overview#implement-controller-methods)
* Page [Upload Troubleshooting](https://www.telerik.com/blazor-ui/documentation/components/upload/troubleshooting)

> caption Using the Upload events

<div class="skip-repl"></div>

<demo metaUrl="client/upload/events/example-2/" height="420"></demo>

```C# UploadController.cs
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace TelerikBlazorApp.Controllers;

[Route("api/[controller]/[action]")]
public class UploadController : ControllerBase
{
    public IWebHostEnvironment HostingEnvironment { get; set; }

    public UploadController(IWebHostEnvironment hostingEnvironment)
    {
        HostingEnvironment = hostingEnvironment;
    }

    [HttpPost]
    public async Task<IActionResult> Save(IFormFile files) // "files" matches the Upload SaveField value
    {
        bool shouldSucceed = Convert.ToBoolean(Request.Form["successData"])
            && Convert.ToBoolean(Request.Headers["successHeader"]);

        if (!shouldSucceed)
        {
            Response.StatusCode = 403;
            await Response.WriteAsync("Upload refused.");
        }
        else if (files != null)
        {
            try
            {
                var rootPath = HostingEnvironment.WebRootPath; // save to wwwroot - Blazor Server only
                //var rootPath = HostingEnvironment.ContentRootPath; // save to Server project root - Blazor Server or WebAssembly
                var saveLocation = Path.Combine(rootPath, files.FileName);

                using (var fileStream = new FileStream(saveLocation, FileMode.Create))
                {
                    await files.CopyToAsync(fileStream);

                    Response.StatusCode = 201;
                    await Response.WriteAsync("Upload successful.");
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                await Response.WriteAsync($"Upload failed. Exception: {ex.Message}");
            }
        }

        return new EmptyResult();
    }

    [HttpPost]
    public async Task<IActionResult> Remove([FromForm] string files) // "files" matches the Upload RemoveField value
    {
        bool shouldSucceed = Convert.ToBoolean(Request.Form["successData"])
            && Convert.ToBoolean(Request.Headers["successHeader"]);

        if (!shouldSucceed)
        {
            Response.StatusCode = 403;
            await Response.WriteAsync("Delete refused.");
        }
        else if (files != null)
        {
            try
            {
                var rootPath = HostingEnvironment.WebRootPath; // delete from wwwroot - Blazor Server only
                //var rootPath = HostingEnvironment.ContentRootPath; // delete from Server project root - Blazor Server or WebAssembly
                var fileLocation = Path.Combine(rootPath, files);

                if (System.IO.File.Exists(fileLocation))
                {
                    System.IO.File.Delete(fileLocation);

                    Response.StatusCode = 200;
                    await Response.WriteAsync($"Delete successful.");
                }
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                await Response.WriteAsync($"Delete failed. Exception: {ex.Message}");
            }
        }

        return new EmptyResult();
    }
}
```

```C# Program.cs
// ...

var builder = WebApplication.CreateBuilder(args);

// ...

builder.Services.AddControllers();

var app = builder.Build();

// ...

app.MapDefaultControllerRoute();

// ...

app.Run();
```

> tip The event is an `EventCallback`. It can be synchronous and return `void`, or asynchronous and return `async Task`. Do not use `async void`.

## See Also

* [Live Demo: Upload Events](https://demos.telerik.com/blazor-ui/upload/events)
* [Upload Overview](https://www.telerik.com/blazor-ui/documentation/components/upload/overview)
* [Upload Methods](https://www.telerik.com/blazor-ui/documentation/components/upload/overview#upload-reference-and-methods)
* [Count all selected and uploaded files](https://www.telerik.com/blazor-ui/documentation/knowledge-base/upload-track-selected-uploaded-files)
