C#MVC文件上传问题

时间:2010-12-06 14:20:06

标签: c# asp.net-mvc

我正在尝试将文件上传到我的mvc项目的服务器上。我写了我的课,

public class MyModule: IHttpModule

which defines the event

void app_BeginRequest (object sender, EventArgs e)

In it, I check the length of the file that the user has selected to send.

if (context.Request.ContentLength> 4096000)
 {
  //What should I write here, that file is not loaded? I tried
   context.Response.Redirect ("address here");
  //but the file is still loaded and then going on Redirect.
 }

1 个答案:

答案 0 :(得分:5)

在ASP.NET MVC中,您通常不会编写http模块来处理文件上载。您编写控制器并在这些控制器内编写动作。 Phil Haack blogged关于上传文件ni ASP.NET MVC:

您有一个包含表单的视图:

<% 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" />
<% } %>

用于处理上传的控制器操作:

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