2

I am working with Asp.net. I'm trying to upload some image to DB. My problem is : the fileUpload is always null.

This is my create

<div class="form-group">
    @Html.LabelFor(model => model.IMG, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <input type="file" name="fileUpload">
    </div>
</div>

This is my controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,NAME,PRICE,QUANTITY,DESCRIPTION,VIEWNUMBER,TIMEUPDATE,ACTIVE,CATE_DEP_ID")] PRODUCTS products)
{
    HttpPostedFileBase fileUpload = Request.Files["fileUpload"];
    if (ModelState.IsValid)
    {
        if (fileUpload != null)
        {
            var fileName = Path.GetFileName(fileUpload.FileName);
            var path = Path.Combine(Server.MapPath("~/Content/Images/Products"), fileName);
            // file is uploaded
            if (System.IO.File.Exists(path))
            {
                ViewBag.ThongBao = "Hình ảnh đã tồn tại";
            }
            else
            {
                fileUpload.SaveAs(path);
            }

            products.IMG = path;
            db.PRODUCTS.Add(products);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }

    ViewBag.CATE_DEP_ID = new SelectList(db.CATE_DEP, "ID", "ID", products.CATE_DEP_ID);
    return View(products);
}
Zabavsky
  • 13,340
  • 8
  • 54
  • 79
Trí Đoàn
  • 21
  • 1
  • 2

1 Answers1

0

Please change following line of code in your Controller. Your code should work fine:

HttpPostedFileBase fileUpload = Request.Files[0];
MicroVirus
  • 5,324
  • 2
  • 28
  • 53
Dilip Oganiya
  • 1,504
  • 12
  • 20