aspnetcore: InputFile OnChange does not work properly
Hello, I was writing some stuff and I found something unexpected with the InputFile so I created a basic example of the issue I am facing by modifying the counter page of the default Blazor server app:
@page "/counter"
<InputFile multiple OnChange="OnChange" class="form-control"></InputFile>
@code {
private async Task OnChange(InputFileChangeEventArgs e) {
foreach (var item in e.GetMultipleFiles()) {
using FileStream fs = new($@"C:\test\{Guid.NewGuid()}.jpg", FileMode.Create);
await item.OpenReadStream().CopyToAsync(fs);
}
}
}
If I upload some jpg images (one or more) I expect them to be copied in the C:\test folder, the file are created but those files are always empty
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 21 (5 by maintainers)
@davidez I just tried out your repro and it failed from the first try. The culprit, however, is in your code. The
OpeanReadAsyncmethod accepts an optionalmaxAllowedSizeparameter, for which the default value is 512000. Because the file being uploaded was larger than that, the method was throwing an exception. I tweaked your slightly simply to demonstrate that it works. Here what you need to change it to:Hope this helps.
Disregard my previous comment. I fixed my issue by adding
@rendermode InteractiveServerto the top of my page. After reading through the docs a few times, I realized I had missed the rendermode part at the top.https://learn.microsoft.com/en-us/aspnet/core/blazor/file-uploads?view=aspnetcore-8.0
You could try calling
await fs.FlushAsync()after you await your call toCopyToAsync. I have seen that fix this 0-byte file problem before.