1

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.
 }
1
  • What are you trying to do -- check that the file doesn't exceed a maximum size? Also, I don't believe you need to create an implementation of IHttpModule to handle file upload -- you can simply use an [HttpPost] action in your controller that takes a HttpPostedFileBase parameter. Commented Dec 6, 2010 at 14:26

1 Answer 1

5

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");
}
Sign up to request clarification or add additional context in comments.

5 Comments

When triggered event Upload, file will already be uploaded to the server. If the file is larger than a certain value, I do not want to load it.
@darin I have used this code to save the file in the directory But I am receiving HttpPostedFileBase null in the controller
@user1006544, you must have forgot something and your code probably doesn't look exactly as the one shown here.
@darin I am showing you my code see this Link I am receiving null in the fill
@user1006544, in the code you have shown your file input doesn't have a name! Look at my code once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.