简体   繁体   中英

C# MVC problem with file upload

I'm trying to make uploading a file to the server at my mvc project. I wrote my class,

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.
 }

In ASP.NET MVC you don't usually write http modules to handle file uploads. You write controllers and inside those controllers you write actions. Phil Haack blogged about uploading files ni ASP.NET MVC:

You have a view containing a form:

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

And a controller action to handle the upload:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM