3

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.

Flood Gravemind
  • 3,773
  • 12
  • 47
  • 79
  • if file.ContentLength is a 32-bit signed integer the max value you can compare it to is 2 billion. That would explain the particular message you got. – Meredith Poor Jul 24 '13 at 22:38
  • possible duplicate of [Is there a way to ignore the maxRequestLength limit of 2GB file uploads?](http://stackoverflow.com/questions/13129746/is-there-a-way-to-ignore-the-maxrequestlength-limit-of-2gb-file-uploads) – Erik Philips Jul 25 '13 at 00:04
  • I don't know if you are trying to upload an exact 4MB file, but remember, 4 megabytes = 4 194 304 bytes. Have you went through the code line by line during a upload request? Do you have error messages if one of the if statements fails? – Tommy Jul 25 '13 at 03:48
  • @Tommy the IF(file.ContentLength < 4000000) is not satisfied even if the file is 100kb text file. The code executes without any stack error but does not save the file. – Flood Gravemind Jul 25 '13 at 09:32
  • What is the reported file.contentLength()? Have you attached the debugger to check the actual reported values from the code? – Tommy Jul 25 '13 at 11:46

2 Answers2

3

Set this value in your web.config

<httpRuntime maxRequestLength="4096"/>

ChrisBint
  • 12,773
  • 6
  • 40
  • 62
0

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);
        }
 }
Abdulhakim Zeinu
  • 3,333
  • 1
  • 30
  • 37