0
@using (Html.BeginForm("Edit", "MyController", FormMethod.Post, new { enctype="multipart/form-data"}))
{
@Html.EditorFor(model => model.Name)
<input type="file" name="fileUpload" id="fileUpload" />
<input type="image" name="imb_save" src="/button_save.gif" alt="" value="Save" />
}

Submitted form and model are passed in this action:

[HttpPost]
public ActionResult Edit(MyModel mymodel, FormCollection forms)
{
         if (string.IsNullOrEmpty(forms["fileUpload"]))
         {
                  //forms["fileUpload"] does not exist
         }
         //TODO: something...
}

Why does not forms contain fileUpload? But it contains other inputs. How can I get content of my uploader? Thanks.

1 Answer 1

4

Take a look at the following blog post for handling file uploads in ASP.NET MVC. You could use HttpPostedFileBase in your controller instead of FormCollection:

[HttpPost]
public ActionResult Edit(MyModel mymodel, HttpPostedFileBase fileUpload)
{
    if (fileUpload != null && fileUpload.ContentLength > 0) 
    {
        // The user uploaded a file => process it here
    }

    //TODO: something...
}

You could also make this fileUpload part of your view model:

public class MyModel
{
    public HttpPostedFileBase FileUpload { get; set; }

    ...
}

and then:

[HttpPost]
public ActionResult Edit(MyModel mymodel)
{
    if (mymodel.FileUpload != null && mymodel.FileUpload.ContentLength > 0) 
    {
        // The user uploaded a file => process it here
    }

    //TODO: something...
}
Sign up to request clarification or add additional context in comments.

5 Comments

But why does such way work properly in this case?
@greatromul, in this example they use Request.Files["FileBlob"] to fetch the actual file, they are not fetching it from FormCollection. So in your code you could do var file = Request.Files["fileUpload"];. But anyway I would strongly recommend you using HttpPostedFileBase.
@greatromul, for which object? Try following the exact steps showed in the blog post. Then adapt to your scenario.
I found reason, but can not resolve it. Index action works only, but i can't understand why.
You are right, Request.Files["fileUpload"] works properly. But I follow your advice and will use trick with model. It is important to not forget, that input name must be the same as property in model. Thanks for help!

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.