How to fix uploading multiple files in Blazor Server?
Cenk
1,021
Reputation points
Hi there,
I am trying to upload multiple images to my Blazor Server project as follows:
Here is the razor page relevant part:
<div class="form-group pt-4 col-6">
<InputFile OnChange="HandleImageUpload" multiple></InputFile>
</div>
Here is the method:
private async Task HandleImageUpload(InputFileChangeEventArgs e)
{
IsLoading = true;
try
{
var files = e.GetMultipleFiles();
var validFiles = new List<IBrowserFile>();
foreach (var file in files)
{
var fileInfo = new System.IO.FileInfo(file.Name);
if (fileInfo.Extension.ToLower() == ".jpg" ||
fileInfo.Extension.ToLower() == ".png" ||
fileInfo.Extension.ToLower() == ".jpeg")
{
validFiles.Add(file);
}
else
{
await _jsRuntime.ToastrError("Please select .jpg/.jpeg/.png file only");
IsLoading = false;
return;
}
}
var imageUrls = await _fileUpload.UploadFiles(validFiles);
Product.ImageUrls.AddRange(imageUrls);
}
catch (Exception ex)
{
await _jsRuntime.ToastrError(ex.Message);
}
finally
{
IsLoading = false;
}
}
Here are the methods in the file upload service:
public async Task<string> UploadFile(IBrowserFile file)
{
if (file == null)
{
throw new ArgumentNullException(nameof(file), "File cannot be null");
}
try
{
FileInfo fileInfo = new(file.Name);
var fileName = Guid.NewGuid().ToString() + fileInfo.Extension;
var folderDirectory = $"{_webHostEnvironment.WebRootPath}\\images\\product";
if (!Directory.Exists(folderDirectory))
{
Directory.CreateDirectory(folderDirectory);
}
var filePath = Path.Combine(folderDirectory, fileName);
await using var fs = new FileStream(filePath, FileMode.Create);
await file.OpenReadStream().CopyToAsync(fs);
var fullPath = $"/images/product/{fileName}";
return fullPath;
}
catch (Exception ex)
{
// Log the exception (you can use a logging framework here)
Console.WriteLine($"Error uploading file: {ex.Message}");
throw; // Re-throw the exception to be handled by the calling code
}
}
public async Task<List<string>> UploadFiles(IEnumerable<IBrowserFile> files)
{
var filePaths = new List<string>();
foreach (var file in files)
{
try
{
var filePath = await UploadFile(file);
filePaths.Add(filePath);
}
catch (Exception ex)
{
// Log the exception (you can use a logging framework here)
Console.WriteLine($"Error uploading file: {ex.Message}");
// Optionally, you can decide whether to continue or break the loop
}
}
return filePaths;
}
I am getting this error on await file.OpenReadStream().CopyToAsync(fs);
Even though I added private const long MaxFileSize = 1024 * 1024 * 15; // 15MB
Microsoft.JSInterop.JSException
HResult=0x80131500
Message=e is null
Qe@http://localhost:7253/_framework/blazor.server.js:1:37025
readFileData@http://localhost:7253/_framework/blazor.server.js:1:36985
beginInvokeJSFromDotNet/s<@http://localhost:7253/_framework/blazor.server.js:1:3047
beginInvokeJSFromDotNet@http://localhost:7253/_framework/blazor.server.js:1:3004
_invokeClientMethod@http://localhost:7253/_framework/blazor.server.js:1:60890
_processIncomingData@http://localhost:7253/_framework/blazor.server.js:1:58279
Xt/this.connection.onreceive@http://localhost:7253/_framework/blazor.server.js:1:51920
connect/</s.onmessage@http://localhost:7253/_framework/blazor.server.js:1:80026
Source=System.Private.CoreLib
StackTrace:
at System.Threading.Tasks.ValueTask`1.get_Result()
at Microsoft.AspNetCore.Components.Forms.BrowserFileStream.<OpenReadStreamAsync>d__29.MoveNext()
at Microsoft.AspNetCore.Components.Forms.BrowserFileStream.<CopyFileDataIntoBuffer>d__30.MoveNext()
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Components.Forms.BrowserFileStream.<ReadAsync>d__28.MoveNext()
at System.IO.Stream.<<CopyToAsync>g__Core|27_0>d.MoveNext()
at TangyWeb_Server.Service.FileUpload.<UploadFile>d__3.MoveNext() in C:\Users\197199\Desktop\E-Commerce\TangyBlazor-master\TangyWeb_Server\Service\FileUpload.cs:line 44
at TangyWeb_Server.Service.FileUpload.<UploadFile>d__3.MoveNext() in C:\Users\197199\Desktop\E-Commerce\TangyBlazor-master\TangyWeb_Server\Service\FileUpload.cs:line 47
This exception was originally thrown at this call stack:
[External Code]
TangyWeb_Server.Service.FileUpload.UploadFile(Microsoft.AspNetCore.Components.Forms.IBrowserFile) in FileUpload.cs
TangyWeb_Server.Service.FileUpload.UploadFile(Microsoft.AspNetCore.Components.Forms.IBrowserFile) in FileUpload.cs
How can I fix it?
Thank you.
Sign in to answer