Gerald Gonzales
Gerald Gonzales

Reputation: 533

Validate upload size

I have the following code below:

MultipartMemoryStreamProvider result = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
HttpContent content = results.Contents.FirstOrDefault(i => i.Headers.ContentDisposition.Name.Contains("FileContent"));

byte[] data = await content.ReadAsByteArrayAsync();

if (data.Length > 51200)
{
    // block upload with more than 50mb of size
}

Now this is not working because even 2mb file is being blocked. I searched and saw that 50mb in kb is 51200.

Upvotes: 1

Views: 1033

Answers (3)

Lara
Lara

Reputation: 3021

Just add this line in your web.config and it will not allow beyond the size specified to be uploaded from application

<httpRuntime executionTimeout="1200" maxRequestLength="15000" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true" />

maxRequestLength="15000" will allow maximum to 15 MB and post which will through exception, similarly you can specify as per your requirement.

Config file will check for upload file size and you do not have to write specific code for the same

Upvotes: 1

Vijunav Vastivch
Vijunav Vastivch

Reputation: 4191

Im not so sure but you can try this:

double filesize = data.Length / 2048

remember 1024kb == 1MB and 1024byte == 1kb that's is why data.Length /2048 to get the Megabyte

The Content value of filesize == MB

 if(filesize>50)

something like that...

Upvotes: 1

Alex
Alex

Reputation: 649

Have you already read official msdn documentation?

The method Length():

gets the length in bytes of the stream.

Actually, 51200 bytes are equals to 0,05 Mb. Have you tried to change it?

If you need to block upload with more than 50mb of size, you need to set it to: 50 Mb = 52,428,800 bytes.

Upvotes: 1

Related Questions