我创建了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兆字节的文件,DefaultRedirect在Opera中运行良好,但在Chrome和IE中不起作用。我还在global.asax的Application_Error ()事件中使用了Response.Redirect ("address here")。它在Chrome和IE中也不起作用。我该怎么办?
发布于 2010-12-07 02:42:56
maxRequestLength以千字节(KB)表示。您将自己的大小设置为2000KB (略小于2MB,因为1MB中有1024KB )。
我不确定为什么它能在一些浏览器中工作,而在另一些浏览器中不能工作,除非一些浏览器正在压缩整个上传内容,而另一些浏览器则不能(我相信HTTP1.1支持)。
哈哈,布莱恩
发布于 2010-12-07 02:44:40
尝尝这个。这段代码已经过测试,并按预期工作。以后尽量不要对字符串变量使用var类型。var是一种动态类型,应该适用于所有文件类型-包括数组。但尝试指定文件类型将有助于减少错误。
我通常将我的公共文件放在公共文件夹中。因此,将其更改为您的文件夹(例如App_Data)
[HttpPost]
public ActionResult test(HttpPostedFileBase file)
{
if (file.ContentLength> 4096000)
{
return RedirectToAction ("FileTooBig");
}
string fileName = Path.GetFileName(file.FileName);
string uploadPath = Server.MapPath("~/Public/uploads/" + fileName);
file.SaveAs(uploadPath);
return View("Index");
}祝好运
发布于 2010-12-07 08:17:50
没有办法阻止文件被上传。IIS在将其传递到ASP.NET堆栈之前接收整个HTTP请求正文。这包括你的多部分表单帖子的所有部分。因此,通过检查file.ContentLength属性,ASP.NET实际上没有机会中断文件的上传。
您可以编写自定义HTTP模块来检查文件大小,但是在收到整个请求之前中止或关闭响应将导致空响应。这意味着没有办法优雅地失败。
我的建议是在实现HTTP模块的同时,在隐藏的iframe中进行文件上传。这样即使出了问题,你的主页也不会崩溃。
每个人都可以和我一起感谢微软的这个惊人的“功能”(队列中的讽刺)。
感谢微软。谢谢。
https://stackoverflow.com/questions/4369418
复制相似问题