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.

greatromul
  • 1,069
  • 2
  • 15
  • 42

1 Answers1

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...
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • But why does such way work properly in this [case](http://stackoverflow.com/questions/297954/uploading-files-with-asp-net-mvc-get-name-but-no-file-stream-what-am-i-doing-w)? – greatromul May 12 '11 at 07:13
  • @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`. – Darin Dimitrov May 12 '11 at 07:14
  • @greatromul, for which object? Try following the exact steps showed in the blog post. Then adapt to your scenario. – Darin Dimitrov May 12 '11 at 07:34
  • I found [reason](http://stackoverflow.com/questions/5975386/fileupload-works-in-index-action-only-asp-net-mvc), but can not resolve it. Index action works only, but i can't understand why. – greatromul May 12 '11 at 08:39
  • 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! – greatromul May 12 '11 at 10:02