8

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
  • 11,730
  • 21
  • 92
  • 169

4 Answers4

27

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
  • 104,599
  • 10
  • 205
  • 202
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
  • 15,427
  • 16
  • 64
  • 91
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
  • 3,939
  • 4
  • 49
  • 62
oziomajnr
  • 1,611
  • 1
  • 14
  • 37
2
var fileSize = file.ContentLength;
if (fileSize > 10 * 1024 * 1024)
{
    // Do whatever..
}
loneshark99
  • 664
  • 4
  • 16