AspNetCore.Docs
AspNetCore.Docs copied to clipboard
CancellationToken use with Blazor InputFile component
Per https://github.com/dotnet/aspnetcore/issues/29979 ...
I have an InputFile component and upload a file with it. The event
OnChangegets 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
CancellationTokenwhen you call into theBrowserFile.OpenReadStream/Stream.ReadAsync.You can have a
CancellationTokenSourceassociated with theInputFilecomponent. At the start of theOnInputFileChangemethod, you can check if a previous upload is still in progress, and if so, callCancellationTokenSource.Cancelon the previous upload. Then you can create a newCancellationTokenSourcefor the next upload, and pass in theCancellationTokenSource.TokenintoBrowserFile.OpenReadStream&ReadAsync.
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: 5ea474d5-234a-f393-8609-892a2deb5d2e
- Version Independent ID: c11d981c-05af-c19d-a333-feedd5978639
- Content: ASP.NET Core Blazor file uploads
- Content Source: aspnetcore/blazor/file-uploads.md
- Product: aspnet-core
- Technology: aspnetcore-blazor
- GitHub Login: @guardrex
- Microsoft Alias: riande