Luis Valencia
Luis Valencia

Reputation: 33998

Request.Files is empty when trying to upload file with mvc

This is my model.

public class Libro
{
    [Key]
    [ScaffoldColumn(false)]
    public int ID { get; set; }

    [Required]
    [MaxLength(300, ErrorMessage = "El Path debe tener como máximo 300 caractéres")]
    [Display(Name = "Ruta de acceso")]
    public string Path { get; set; }

    [Required]
    [MaxLength(80, ErrorMessage = "El nombre debe tener como máximo 80 caractéres")]
    public string Nombre { get; set; }

    [Required]
    [Display(Name = "Ruta de acceso")]
    public HttpPostedFileBase File { get; set; }

    //Relations
    public virtual ICollection<Hoja> Hojas { get; set; }
}

Here's my view:

@model xx.Models.Libro

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Libro</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(x => x.File, new { type = "file" })
                @*@Html.EditorFor(model => model.File, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })*@
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Nombre, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Nombre, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Nombre, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div> 

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Nombre")] Libro libro)
{
    if (ModelState.IsValid)
    {
        foreach (string upload in Request.Files)
        {
            if (Request.Files[upload].ContentLength == 0) continue;
            string pathToSave = Server.MapPath("~/App_Data/Uploads");
            string filename = Path.GetFileName(Request.Files[upload].FileName);
            Request.Files[upload].SaveAs(Path.Combine(pathToSave, filename));
            libro.Path = Path.Combine(pathToSave, filename);
            db.Libro.Add(libro);
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }

    return View(libro);
} 

Upvotes: 2

Views: 3772

Answers (2)

user449689
user449689

Reputation: 3154

Try changing your BeginForm to:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, 
      new { enctype = "multipart/form-data" }))

Upvotes: 3

hutchonoid
hutchonoid

Reputation: 33306

You need to set the encType on the form to multipart/form-data;

@using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, 
new { encType="multipart/form-data" }))

The file will also be available from within your model i.e. libro.File.

Upvotes: 10

Related Questions