c# - 使用 httpRuntime maxRequestLength 进行 mvc 文件上传

标签 c# asp.net-mvc

我创建了mvc项目并想要上传文件。我在web.config中注册了

<httpRuntime maxRequestLength="2000"/> 
<customErrors mode="On" redirectMode="ResponseRedirect" defaultRedirect="address here"> </ customErrors>, in Index.aspx <% using (Html.BeginForm ("upload", "home", FormMethod.Post, 
    new {enctype = "multipart / form-data"})) {%> 
    <label for="file"> Filename: </ label> 
    <input type="file" name="file" id="file" /> 

    <input type="submit" /> 
<%}%> 

在 HomeController.cs 中

[HttpPost] 
public ActionResult Upload (HttpPostedFileBase file) 
{ 
    if (file! = null & & file.ContentLength> 0) 
    { 
        if (file.ContentLength> 4096000) 
        { 
            return RedirectToAction ("FileTooBig"); 
        } 
        var fileName = Path.GetFileName (file.FileName); 
        var path = Path.Combine (Server.MapPath ("~ / App_Data / uploads"), fileName); 
        file.SaveAs (path); 
    } 
    return RedirectToAction ("Index"); 
} 

如果我附加超过 2 MB 的文件,DefaultRedirect 在 Opera 中可以完美工作,但在 Chrome 和 IE 中不起作用。我还在 global.asax 的 Application_Error () 事件中使用了 Response.Redirect (“地址此处”)。它也不适用于 Chrome 和 IE。我该怎么办?

最佳答案

maxRequestLength 以千字节 (KB) 为单位。您将其设置为 2000KB(略小于 2MB,因为 1MB 中有 1024KB)。

我不确定为什么它在某些浏览器中工作,而在其他浏览器中不起作用,除非有些浏览器压缩整个上传内容,而另一些则不压缩(我相信这是 HTTP 1.1 支持的)。

HTH, 布赖恩

关于c# - 使用 httpRuntime maxRequestLength 进行 mvc 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4369418/

相关文章:

c# - 如何从 MySql 数据库获取日期到 C# DateTime 对象?

c# - TreeView 自定义 DrawNode .NET 3.5 Windows 窗体

c# - 在 C# 中解析 PayPal SOAP 响应

c# - 按模型分组并选择模型

asp.net-mvc - ASP.NET MVC + WebForms - 路由冲突

c# - 在 C++ 和 C# 中使用递归求矩阵的行列式

c# - 将 XML XDocument 增量写入磁盘,保留有效的 XML

c# - 有了区域,我可以轻松地将我的应用程序分解成不同的模块吗?

asp.net-mvc - 我的 MVC 4 应用程序无法在 Azure 上加载。我如何找出问题所在?

javascript - 无法使用 Ajax 将数据列表从 Controller 返回到 View 中的下拉列表。我收到未定义的未定义错误