0

As there is no helper for File Input, how can we safely handle a file input?

If it better just to have a button

<input type="button" value="Upload File" />

and handle this in a new pop-up page/window?

shall I have the

<input type="file" value="Upload File" />

but how would I handle this in the code?

#region General
//
// GET: /Content/General
public ActionResult General()
{
    GeneralModel model = new GeneralModel();
    return View(model);
}

[HttpPost]
public void General(GeneralModel model)
{

}

#endregion

The model will not be populated with the file so I need to do something else ... just don't know what :(

Any help is greatly appreciated.

Thank you.

1 Answer 1

1

The input should have a name:

<input type="file" name="File" />

Then to handle the uploaded file you could add a property to your view model:

public class GeneralModel
{
    // The name of the property corresponds to the name of the input
    public HttpPostedFileBase File { get; set; }
    ...
}

and finally in your controller action handle the file upload:

[HttpPost]
public void General(GeneralModel model)
{
    var file = model.File;
    if (file != null && file.ContentLength > 0)
    {
        // The user selected a file to upload => handle it
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
        file.SaveAs(path);
    }
    return View(model);    
}

Phil Haack blogged about file uploads in ASP.NET MVC.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, you just forgot that I need <% using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { enctype = "multipart/form-data" })) { %> :)
I thought that was obvious :-) multipart/form-data is always required for file uploads.
I do have to handle 2 forms right? one for images and other for the rest of the properties...?
Not necessarily. One form can handle for both file uploads and normal inputs as long as you have the correct enctype.
Got it, it handles everything :) many thanks for the heads up.

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.