2016-08-09 3 views
0

MVC 응용 프로그램을 만들고 있습니다. Entity 프레임 워크를 사용하고 있습니다. 마지막으로 파일 업로드 및보기를 만들려고합니다. 나는 내가 오류를파일 업로드 및 MVC에서 작동하지 않는보기

{"Object reference not set to an instance of an object."} 
Inner Exception null 

사실은 내가 사용하고 엔티티 프레임 워크 모델을 점점 업로드 file.click보기 버튼을 엽니 다보기 버튼이와 나는 프로젝트를 생성 한 후 컨트롤러 프로젝트 컨트롤러 업로드를

public async Task<ActionResult> FileManager(int ProjectId = 0) 
    { 
     ReadCookieValue cookie = new ReadCookieValue(); 

     clientId = cookie.readuserinfo().ClientId; 
     userId = cookie.readuserinfo().Id; 
     roleId = cookie.readuserinfo().RoleId; 
     var model = await _project.FilesList(ProjectId, clientId); 
     return View(model); 
    } 
    public async Task<ActionResult> FileUpload(int ProjectId = 0) 
    { 
     return View(ProjectId); 
    } 
    [HttpPost] 
    public async Task<ActionResult> FileUploadHandler(int ProjectId = 0) 
    { 
     ReadCookieValue cookie = new ReadCookieValue(); 

     clientId = cookie.readuserinfo().ClientId; 
     userId = cookie.readuserinfo().Id; 
     roleId = cookie.readuserinfo().RoleId; 
     if (ProjectId != 0) 
     { 
      foreach (var fileKey in Request.Files.AllKeys) 
      { 
       ProjectFileModel model = null; 
       var file = Request.Files[fileKey]; 
       try 
       { 
        if (file != null) 
        { 
         model = new ProjectFileModel(); 
         var fileName = Path.GetFileName(file.FileName); 
         var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), clientId.ToString(), ProjectId.ToString()); 
         if (!Directory.Exists(path)) 
         { 
          Directory.CreateDirectory(path); 
         } 
         var path1 = Path.Combine(path, fileName); 
         model.ProjectId = ProjectId; 
         model.FileName = fileName; 
         model.FilePath = path; 
         model.UploadedBy = User.Identity.Name; 
         model.UploadedDate = DateTime.UtcNow; 
         model.ClientId = clientId; 
         var result = await _project.UploadFiles(model); 
         file.SaveAs(path1); 

        } 
       } 
       catch (Exception ex) 
       { 
        return Json(new { Message = "Error in saving file" }); 
       } 
      } 
     } 
     else 
     { 
      return Json(new { Message = "Please Select Project" }); 
     } 
     return Json(new { Message = "File saved" }); 
    } 

를 제출해야 자신의 모델을 사용합니다. FileUploadHandler 컨트롤러 Action.Here FileuploadHandler 코드를

public async Task<ActionResult> FileUploadHandler(int ProjectId = 0) 
     { 
      ReadCookieValue cookie = new ReadCookieValue(); 

      clientId = cookie.readuserinfo().ClientId; 
      userId = cookie.readuserinfo().Id; 
      roleId = cookie.readuserinfo().RoleId; 
      if (ProjectId != 0) 
      { 
       foreach (var fileKey in Request.Files.AllKeys) 
       { 
        ProjectFileModel model = null; 
        var file = Request.Files[fileKey]; 
        try 
        { 
         if (file != null) 
         { 
          model = new ProjectFileModel(); 
          var fileName = Path.GetFileName(file.FileName); 
          var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), clientId.ToString(), ProjectId.ToString()); 
          if (!Directory.Exists(path)) 
          { 
           Directory.CreateDirectory(path); 
          } 
          var path1 = Path.Combine(path, fileName); 
          model.ProjectId = ProjectId; 
          model.FileName = fileName; 
          model.FilePath = path; 
          model.UploadedBy = User.Identity.Name; 
          model.UploadedDate = DateTime.UtcNow; 
          model.ClientId = clientId; 
          var result = await _project.UploadFiles(model); 
          file.SaveAs(path1); 

         } 
        } 
        catch (Exception ex) 
        { 
         return Json(new { Message = "Error in saving file" }); 
        } 
       } 
      } 
      else 
      { 
       return Json(new { Message = "Please Select Project" }); 
      } 
      return Json(new { Message = "File saved" }); 
     } 

이전이 코드를 사용하여 여기

<div class="ibox-content"> 
<ng-form id="my-awesome-dropzone" class="dropzone" action="@Url.Action("FileUploadHandler", "Projects")" method="post" enctype="multipart/form-data"> 
<div class="dropzone-previews"></div> 
    <button type="submit" class="btn btn-primary pull-right">Submit this form!</button> 
    </ng-form> 

    </div> 

파일 업로드 코드는 엔티티 프레임 워크 아웃으로 개발한다. 이후 나는 두 모델 전 모델 폴더 아래에 edmx 볼 수있는 클래스의 종류와 내가 엔티티 프레임 워크 모델 유형하지 않고 엔티티 프레임 워크의 내부 이전 방법에 따라이

namespace Inspinia_MVC5.Entityframework 
{ 
    using System; 

    public partial class ProjectsList_Result 
    { 
     public int ProjectId { get; set; } 
     public string ProjectName { get; set; } 
     public Nullable<System.DateTime> StartDate { get; set; } 
     public Nullable<System.DateTime> EndDate { get; set; } 
     public Nullable<bool> IsActive { get; set; } 
     public Nullable<System.DateTime> CreatedDate { get; set; } 
     public string CreatedBy { get; set; } 
     public Nullable<System.DateTime> UpdatedDate { get; set; } 
     public string UpdatedBy { get; set; } 
     public int ClientId { get; set; } 
     public string Employees { get; set; } 
     public bool IsAnalyticsStart { get; set; } 
     public bool IsAnalyticsEnd { get; set; } 
     public string ReportType { get; set; } 
    } 
} 

을 보았다이 생성 엔티티 프레임 워크 모델을

namespace Inspinia_MVC5.Models 
{ 
    public class ProjectsModel 
    { 
     public int ProjectId { get; set; } 
     public string ProjectName { get; set; } 
     [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
     public DateTime StartDate { get; set; } = DateTime.Now; 
     [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")] 
     public DateTime EndDate { get; set; } = DateTime.Now; 
     public bool IsActive { get; set; } 
     public DateTime CreatedDate { get; set; } 
     public string CreatedBy { get; set; } 
     public DateTime UpdatedDate { get; set; } 
     public string UpdatedBy { get; set; } 
     public int ClientId { get; set; } 
     public List<LoginModelViewModel> AllEmployees { get; set; } 
     public string Employees { get; set; } 
     public bool IsAnalyticsStart { get; set; } 
     public bool IsAnalyticsEnd { get; set; } 
     public List<ReportType> reportTypes { get; set; } 
     public string ReportType { get; set; } 
     public string Designation { get; set; } 
    } 
} 
내 솔루션 폴더에있는

App_start/Uploads/1/1입니다. 코드를 실행하면 오류가 발생합니다.

{"Object reference not set to an instance of an object."} 
    Inner Exception null 

누구에게 어떤 실수를했는지 알려주세요. 누구든지이 문제를 도와 주시겠습니까?

+0

을 사용하고 가정하자 당신이에 디버거를 사용한 적이 서버가 null인지 확인하려면? 쿠키 일 수 있니? 그럼 뭐든지 될 수 있습니다! – Heberda

+0

엔티티 모델과 내 모델을 동시에 사용할 수 있습니까? –

+0

예, 어떤 의미입니까? Visual Studio를 사용하고 있습니까? 예외가 발생하면 로컬 호스트를 사용하여 디버깅을 중지 한 다음 null 요소를 검사 할 수 있습니다. 그게 우리가 필요로하는 정보입니다 :) – Heberda

답변

-1

파일 업로드 : - 당신이 업로드 파일에 대한 코드를 작성하는 방법 예을 표시하고

나는 비디오 표에 파일을 업로드하고 PostVideo 모델

[HttpPost] 
public ActionResult PostAVideo(PostVideo model, HttpPostedFileBase file) 
    { 
     if (ModelState.IsValid && file.ContentLength > 0) 
     { 
      string filePath = "/Uploads/" + WebSecurity.CurrentUserName + "/" + model.Category; 
      if (!Directory.Exists(Server.MapPath(filePath))) 
      { 
       Directory.CreateDirectory(Server.MapPath(filePath)); 
      } 

      var fileName = Path.GetFileName(file.FileName); 
      var path = Path.Combine(Server.MapPath(filePath), fileName); 
      file.SaveAs(path); 

      Video _model = new Video(); 
      _model.Title = model.Title; 
      _model.Path = filePath + "/" + fileName; 
      _model.Keyword = model.Keyword; 
      _model.Description = model.Description; 
      _model.Categories = model.Category; 
      _model.CreatedDate = model.CreatedDate; 
      _model.UserName = User.Identity.Name; 
      _model.UserId = WebSecurity.CurrentUserId; 
      _model.Name = fileName; 
      _model.IsDownload = model.IsDownload; 
      _model.IsCommented = model.IsComment; 
      _model.Poster = WebSecurity.CurrentUserName; 
      db.Video.Add(_model); 
      db.SaveChanges(); 
      ModelState.Clear(); 


     } 

     return View(); 
    } 
+0

당신의 대답은 당신이 왜 이런 식으로해야하는지, 그리고 그 질문의 코드와 어떻게 다른지 설명하는 데 큰 도움이 될 것입니다. –

관련 문제