Matthew Verstraete
Matthew Verstraete

Reputation: 6791

File upload not working but not throwing any errors

I am trying to upload allow file uploads in my MVC app but when I test it out the page simply refresh, does not show any errors, and does not upload the file so I am at a complete loos as to what is wrong.

View:

<form action="" method="post" enctype="multipart/form-data">

    <label for="file">Filenname:</label>
    <input type="file" name="file" id="file" />
    <input type="submit" />
</form>

Controller:

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        if (file.ContentLength > 0)
        {
            var filename = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/"), filename);
            file.SaveAs(path);
        }

        return RedirectToAction("Index");
    }

Upvotes: 0

Views: 103

Answers (2)

Peter Smith
Peter Smith

Reputation: 5550

Try:

<form action="Controller/Index" method="post" enctype="multipart/form-data">

    <label for="file">Filenname:</label>
    <input type="file" name="file" id="file" />
    <input type="submit" />
</form>

Upvotes: 2

SOfanatic
SOfanatic

Reputation: 5573

Haven't actually tried it, but my guess is that it's because you are not using Html.BeginForm and you are using simply <form>. Try this:

@using (Html.BeginForm("Index","Upload",FormMethod.Post, new {enctype="multipart/form-data"}))
{
    <input type="file" name ="file" id ="file"/>
    <input type="submit">
}

Upvotes: 0

Related Questions