在MVC 4中上传代码FIle Exist Validation Code

时间:2014-04-18 09:30:27

标签: asp.net-mvc asp.net-mvc-4

这是我的文件上传控制器:

[HttpPost]
        public ActionResult Create(AdulLiteracyTeachers adulliteracyteachers, HttpPostedFileBase[] files)
        {
            foreach (HttpPostedFileBase file in files)
            {
                string path = System.IO.Path.Combine(Server.MapPath("~/Content/Uploads/"), System.IO.Path.GetFileName(file.FileName));
                file.SaveAs(path);
                adulliteracyteachers.Image = file.FileName;
            }
            if (ModelState.IsValid)
            {

                db.AdulLiteracyTeachers.Add(adulliteracyteachers);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.DistID = new SelectList(db.Districts, "DistID", "DistName", adulliteracyteachers.DistID);
            return View(adulliteracyteachers);
        }

如何将Check If文件已存在上传另一个?

1 个答案:

答案 0 :(得分:0)

假设在视图中:

<input type="file" id="FileUpload" name="FileUpload"/>

你需要在行动中这样做:

string path = System.IO.Path.Combine(Server.MapPath("~/Content/Uploads/"), System.IO.Path.GetFileName(file.FileName));

if (System.IO.File.Exists(path))
{ 
    //Other code

this.ModelState.AddModelError("FileUpload", "File Already exists");

return View(adulliteracyteachers);
}

else
{
 // upload and save in db
}