一、网页代码
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ <input type="file" name="file" /> <input type="submit" value="上传" />}二、后台代码
public ActionResult FileUpload()
{ HttpPostedFileBase file = Request.Files["file"]; if (file != null) { string filepath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.FileName)); file.SaveAs(filepath); return RedirectToAction("Index", "Home"); } else { return View(); } }三、配置文件
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" executionTimeout="3600" />
四、说明
maxRequestLength 文件大小限制
executionTimeout 最长响应时间
功能说明:将指定文件上传到网站目录Uploads下
补充:
文件大小限制另一种方法是修改.NET FrameWork:
(1) 修改 C:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/CONFIG 目录下的machine.config 文件。
(2) 查找 "<httpruntime" 在这一行将 maxRequestLength的值改为理想的值,比如想要8M,就输入8192.
这样,你的任何一个 web 工程都可以上传最大8M的文件。
顺便说下IIS中限制上传文件大小的修改方法:
(1)首先要到进程中把IIS服务关了,即把inetinfo.exe进程关了。
(2)在系统目录中找到:windows/system32/inesrv/metabase.xml”文件,找个文本编辑器打开,查找AspMaxRequestEntityAllowed="204800"这一项,这就是iis上传文件的默认大小了,默认为204800Byte,也就是200KB,将它改为需要的大小就可以了。