简体   繁体   English

C#中文件大小服务器端的限制

[英]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我目前正在 MVC4 中上传文件,但在我的控制器中,我试图将文件大小限制为最大 4MB,但收到以下警告

comparison to integral constant is useless

using Haacks example使用Haacks示例

[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.由于file.ContentLength是一个我无法控制的int我不知道解决这个问题的方法是什么。 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.编辑对于那些可能想指出40000000004gb您是对的。 But even if I replace it with 4000000 my action completes sucessfully but does not save the file as my If() is not satisfied ie file.ContentLength < 4000000 returns false.但是,即使我用4000000替换它,我的操作也会成功完成,但不会保存文件,因为我的If()不满意,即file.ContentLength < 4000000返回 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.编辑这不是一个重复的问题我想将我的文件大小限制在某个限制而不是忽略 IIS 中的文件大小限制。

在您的 web.config 中设置此值

<httpRuntime maxRequestLength="4096"/>

For those who are using IFormFile you can use the following.对于那些使用IFormFile您可以使用以下内容。

[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);
        }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM