9

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.

Community
  • 1
  • 1
Casey Crookston
  • 13,016
  • 24
  • 107
  • 193

4 Answers4

31

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
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
3

You can use this method to convert the bytes you got to MB:

static double ConvertBytesToMegabytes(long bytes)
{
    return (bytes / 1024f) / 1024f;
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
2

Prefixes for multiples of bytes (B):
1024 bytes = 1kilobyte
1024 kilobyte = 1megabyte

double ConvertBytesToMegabytes(long bytes)
{
    return (bytes / 1024f) / 1024f;
} 

var fileSize = imageFile.ContentLength;

if (ConvertBytesToMegabytes(fileSize ) > 10f)
{
    // image is too large
}
Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
oziomajnr
  • 1,671
  • 1
  • 15
  • 39
2
var fileSize = file.ContentLength;
if (fileSize > 10 * 1024 * 1024)
{
    // Do whatever..
}
loneshark99
  • 706
  • 5
  • 16