Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/Components/Web.JS/src/InputFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ function init(callbackWrapper: any, elem: InputElement): void {

callbackWrapper.invokeMethodAsync('NotifyChange', fileList);
});

// The 'cancel' event is fired when the user cancels the file picker dialog.
// This event is part of the HTML5 standard and is supported in modern browsers.
// For browsers that don't support this event, it will be silently ignored.
elem.addEventListener('cancel', function(): void {
// Notify with an empty list when the file dialog is cancelled.
elem._blazorFilesById = {};
callbackWrapper.invokeMethodAsync('NotifyChange', []);
});
}

async function toImageFile(elem: InputElement, fileId: number, format: string, maxWidth: number, maxHeight: number): Promise<BrowserFile> {
Expand Down
25 changes: 25 additions & 0 deletions src/Components/test/E2ETest/Tests/InputFileTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,31 @@ public void ThrowsWhenOversizedFileIsSelected()
Browser.Equal("Supplied file with size 32 bytes exceeds the maximum of 10 bytes.", () => exceptionMessage.Text);
}

[Fact]
public void CanClearFilesByInvokingCancelEvent()
{
// Upload a file first
var file = TempFile.Create(_tempDirectory, "txt", "This is a test file.");
var inputFile = Browser.Exists(By.Id("input-file"));
inputFile.SendKeys(file.Path);

// Verify the file was uploaded
var fileContainer = Browser.Exists(By.Id($"file-{file.Name}"));

// Get the file count element
var fileCount = Browser.Exists(By.Id("file-count"));
Browser.Equal("1", () => fileCount.Text);

// Trigger the cancel event via JavaScript to simulate canceling the file dialog
Browser.ExecuteJavaScript(@"
const inputElement = document.getElementById('input-file');
inputElement.dispatchEvent(new Event('cancel'));
");

// Wait a moment for the event to be processed and verify the file list was cleared
Browser.Equal("0", () => Browser.Exists(By.Id("file-count")).Text);
}

public void Dispose()
{
Directory.Delete(_tempDirectory, recursive: true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Max allowed files:
<InputFile OnChange="LoadFiles" id="input-file" multiple />
<br />

<span id="file-count">@loadedFiles.Count</span>
<span id="exception-message">@exceptionMessage</span>

@if (isLoading)
Expand Down
Loading