I need to verify that a file upload by a user does not exceed 10mb. Will this get the job done?
var fileSize = imageFile.ContentLength;
if ((fileSize * 131072) > 10)
{
// image is too large
}
I've been looking at this thread, and this one... but neither gets me all the way there. I'm using this as the conversion ratio.
.ContentLength
gets the size in bytes. Then I need to convert it to mb.
Since you are given the size in bytes, you need to divide by 1048576
(i.e. 1024 * 1024
):
var fileSize = imageFile.ContentLength;
if ((fileSize / 1048576.0) > 10)
{
// image is too large
}
But the calculation is a bit easier to read if you pre-calculate the number of bytes in 10mb:
private const int TenMegaBytes = 10 * 1024 * 1024;
var fileSize = imageFile.ContentLength;
if ((fileSize > TenMegaBytes)
{
// image is too large
}
You can use this method to convert the bytes
you got to MB:
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With