Flood Gravemind
Flood Gravemind

Reputation: 3803

Limit on a file size server side in C#

I am currently uploading files in MVC4 but in my controller I tried to limit the file size to 4MB max but got the following warning

comparison to integral constant is useless

using Haacks example

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
if (file.ContentLength < 4000000000 )
{
   var fileName = System.IO.Path.GetFileName(file.FileName);
   var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
   file.SaveAs(path);
 }

When I run the code I get the error

Maximum request length exceeded.

Since file.ContentLength is an int over which I have no control I do not know what is the way around this. Can anyone help me on how to limit the file size server side.

Edit To those that might want to point out that 4000000000 is 4gb you are correct. But even if I replace it with 4000000 my action completes sucessfully but does not save the file as my If() is not satisfied i.e file.ContentLength < 4000000 returns false.

Edit This is not a duplicate question I want to limit my file size to a certain limit not ignore the file size limit in IIS.

Upvotes: 3

Views: 4661

Answers (2)

Abdulhakim Zeinu
Abdulhakim Zeinu

Reputation: 3829

For those who are using IFormFile you can use the following.

[HttpPost]
public ActionResult Upload(IFormFile file)
{
      int fourMB = 4 * 1024 * 1024;
      var fileSize = file.Length;//Get the file length in bytes
      if (fileSize / 1048576.0 > fourMB) //1048576 (i.e. 1024 * 1024):
        {
          var fileName = System.IO.Path.GetFileName(file.FileName);
          var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
          file.SaveAs(path);
        }
 }

Upvotes: 0

Kinexus
Kinexus

Reputation: 12904

Set this value in your web.config

<httpRuntime maxRequestLength="4096"/>

Upvotes: 3

Related Questions