我创建了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/