AspNetCore.Docs icon indicating copy to clipboard operation
AspNetCore.Docs copied to clipboard

CancellationToken use with Blazor InputFile component

Open guardrex opened this issue 3 years ago • 0 comments

Per https://github.com/dotnet/aspnetcore/issues/29979 ...

I have an InputFile component and upload a file with it. The event OnChange gets raised fine. Now I click again on the browse button to change my uploaded document(s) and click on cancel. The component says nothing is selected now but the event doesn't raise again. So how should I detect that the user has deleted his/her upload?

Tanay answer:

This is something that can already be accomplished by using a CancellationToken when you call into the BrowserFile.OpenReadStream / Stream.ReadAsync.

You can have a CancellationTokenSource associated with the InputFile component. At the start of the OnInputFileChange method, you can check if a previous upload is still in progress, and if so, call CancellationTokenSource.Cancel on the previous upload. Then you can create a new CancellationTokenSource for the next upload, and pass in the CancellationTokenSource.Token into BrowserFile.OpenReadStream & ReadAsync.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

guardrex avatar Jul 21 '22 10:07 guardrex