0

According to the ASP.NET Core Blazor file uploads:

OpenReadStream enforces a maximum size in bytes of its Stream. Reading one file or multiple files larger than 500 KB results in an exception. This limit prevents developers from accidentally reading large files into memory. The maxAllowedSize parameter of OpenReadStream can be used to specify a larger size if required.

With this example:

const long maxAllowedSize = 3L * 1024L * 1024L; //3 MB limit
await using FileStream fs = new(path, FileMode.Create);
await browserFile.OpenReadStream(maxAllowedSize).CopyToAsync(fs);

If I can use OpenReadStream to specify the maxAllowedSize, I can avoid file sizes higher than the specified size.

Now, how should I get the image file dimension and validate it to prevent it from being uploaded?

I need to allow only image dimensions between 330x330 and 5000x5000, and I need to manage this programmatically to inform the user based on its validity.

Note that I'm using the InputFileChangeEventArgs for this instance.

I would greatly appreciate any help!

4
  • 3
    You will need to at minimum read the image file header to determine the image size. This might help: stackoverflow.com/questions/111345/… Commented Aug 8 at 7:41
  • Open the data as an image and check its dimensions? A stream is in no way guaranteed to even represent an image. You could maybe just read the image header to get the size, but eventually you should validate the entire image file. Commented Aug 8 at 7:43
  • @MatthewWatson, I was wondering if Blazor has an existing method or class, or the simplest way to achieve this. Commented Aug 8 at 7:49
  • 1
    Blazor can't do things that the browser can't or that HTTP doesn't provide. Neither the input type="file" nor the HTTP headers contain image metadata. Something has to read that image metadata. The browser can detect the MIME type but doesn't try to read anything else. Commented Aug 8 at 7:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.