Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check size of uploaded file in mb

Tags:

c#

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.

like image 883
Casey Crookston Avatar asked Apr 25 '17 17:04

Casey Crookston


2 Answers

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
}
like image 154
DavidG Avatar answered Sep 19 '22 15:09

DavidG


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

static double ConvertBytesToMegabytes(long bytes)
{
    return (bytes / 1024f) / 1024f;
}
like image 23
Koby Douek Avatar answered Sep 23 '22 15:09

Koby Douek