I have this code in my HomeController
[HttpPost]
public ActionResult NewRequest(int? id, FormCollection form, HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(uploadFile.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/Documents/Files"), fileName);
uploadFile.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
And my NewRequest view is this
@using (Html.BeginForm("NewRequest", "Controllers", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<input type="file" name="uploadFile" />
<input type="submit" value="Upload" />
}
The problem is that the uploaded file, .txt file f.x. is always null.
Your given code is fine. The only case I can think otherwise is you route config is probably not right.
I've tested with this config and it worked like a charm.
routes.MapRoute(
name: "NewRequest",
url: "Controllers/NewRequest",
defaults: new { controller = "Controllers", action = "NewRequest" }
);