2016-08-06 2 views
0

Привет всем вам я столкнулся с проблемой на загрузку файла и сохранить его в папку вот мой взглядФайл не загружая в ASP.Net MVC

<div class="admin-empty-dashboard"> 
@using (Html.BeginForm("UploadResumes", "Employee", new { enctype = "multipart/form-data" })) 
{ 

    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 
    <div class="icon"> 
     <i class="ion-ios-book-outline"></i> 
    </div> 

    <h4>Welcome @Model.FullName!</h4> 
    <p>@ViewBag.Error</p> 
    <div class="form-group bootstrap-fileinput-style-01"> 
     <label>Upload Resume</label> 
     <input type="file" name="file" required="required" class="btn btn-primary" style="margin-left:265px" accept="application/msword,text/plain, application/pdf"> 
     <span class="font12 font-italic">** File must not bigger than 2MB</span> 
    </div> 

    <input type="submit" name="name" class="btn btn-primary" value="UploadResumes" /> 
} 

</div> 

и вот моя проблема контроллеров действий заключается в том, что значение объекта HttpPostedFileBase всегда равно null, и я запустил Request.Files.Count, это также дает мне нуль, где проблема?

public ActionResult UploadResumes(HttpPostedFileBase file) 
{ 
    if (Session["UserID"] != null && Session["UserName"] != null && Session["EmployeeID"] != null) 
    { 
     int id = Convert.ToInt32(Session["EmployeeID"]); 
     string[] allowedExtenssions = new string[] { ".pdf", ".doc", ".docx" }; 
     string cvPath = "~/cvs/Employee_cvs/"; 
     if (!Directory.Exists(Server.MapPath(cvPath))) 
      Directory.CreateDirectory(Server.MapPath(cvPath)); 

     MyDbContext db=new MyDbContext(); 
     tblEmployee employee = (from s in db.tblEmployees where s.UserId == id select s).FirstOrDefault(); 

     // HttpPostedFileBase cv = Request.Files["CV"]; 
     if (file != null) 
     { 
      if (file.ContentLength > 0) 
      { 

       string ext = Path.GetExtension(file.FileName); 
       if (allowedExtenssions.Contains(ext.ToLower())) 
       { 
        string fileName = DateTime.Now.Ticks + ext; 
        string filePath = cvPath + fileName; 
        string serverPath = Server.MapPath(filePath); 
        file.SaveAs(serverPath); 
        employee.cvUrl = filePath; 
       } 

      } 
      ViewBag.Error = "Some Error Occured"; 
     } 

     return RedirectToAction("Dashboard"); 

    } 
    else 
    { 
     return RedirectToAction("Login", "User"); 
    } 
} 
+0

Возможный дубликат (HTTP [Почему MVC HttpPostedFileBase всегда нуль?]: //stackoverflow.com/questions/38713956/why-is-mvc-httppostedfilebase-always-null) – mmushtaq

+0

Уважаемый Пожалуйста, решите мою проблему Я буду очень благодарен всем вам –

+0

Добавили ли вы [HttpPost] перед своим c действие ontroller? –

ответ

1

Update, как показано ниже, и проверить

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

} 

Также

[HttpPost] 
public ActionResult UploadResumes(HttpPostedFileBase file) 
{ 
} 
+0

Спасибо, мир Это сработало для меня ............... –

0

Попробуйте изменить параметры на контроллере для

public ActionResult UploadResumes(Model yourModel, HttpHostedFileBase file) 
0

В большинстве моих контроллеров, которые требуют файл для загрузки, как правило, массив на основе. Убедитесь, вы действуете параметры массив следующим образом:

public ActionResult UploadResumes(HttpPostedFileBase[] files){ 
}