Home > Enterprise >  Validation for attribute in blazor
Validation for attribute in blazor

Time:09-16

I'm learning C# with blazor, I wanted to know how I can validate an input of type file, so that it doesn't allow files larger than 3MB

CodePudding user response:

This example explains how to upload files(in svg format) in Blazor with the InputFile component. Pay attention to the variable maxFileSize that set the maximum number of bytes that can be supplied by the Stream.

FileUpload.razor.cs

private bool fileUploading;
private string filePath = "C:\\fileFolder\\file.svg";
private const int maxFileSize= 3 * 1024 * 1024; //3MB max size

private async Task UploadSvgFileAsync(InputFileChangeEventArgs e)
{
  fileUploading = true;
  try
  {
    string fileExtension = Path.GetExtension(e.File.Name);
    if (!fileExtension.Equals(".svg", StringComparison.OrdinalIgnoreCase))
      throw new Exception("SVG file is required.");

    var stream = e.File.OpenReadStream(maxFileSize);
    await using FileStream fs = new(filePath, FileMode.Create);
    await stream.CopyToAsync(fs);
  }
  catch (Exception ex)
  {
    //some error handling
  }
  fileUploading = false;
}

And in your FileUpload.razor component:

@if (fileUploading )
{
  <span>- File Uploading...</span>
}
<InputFile OnChange="@UploadSvgFileAsync" />

I recommend reading the following articles to learn how to properly work with files in Blazor apps:

File Uploads

File Downloads

CodePudding user response:

FileInfo file = new FileInfo(yourFile);

get the files byte size: var fileBytes = file.Length;

turn bytes to MBs: var fileMBs = fileBytes / (1024*1024)

  • Related