文件上传和视图不工作在MVC

本文关键字:工作 MVC 视图 文件 | 更新日期: 2023-09-27 18:01:40

我正在创建MVC应用程序,我使用实体框架。最后要创建文件上传和查看。我有控制器项目控制器文件上传

   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" });
    }

我创建项目后,我有查看按钮打开上传文件。点击查看按钮出现错误

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

实际上我是使用实体框架模型和我使用自己的模型。

文件上传代码

   <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>

这里使用FileUploadHandler控制器动作。此处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" });
        }

之前的代码开发与我们的实体框架。在使用这个创建的实体框架模型之后,我看到了两个模型类型的类,我可以在模型文件夹和

下看到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; }
    }
}

我在实体框架内部有Follow previous方法,没有实体框架模型类型

 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
谁能告诉我我做错了什么?请有人帮助解决这个问题吗?

文件上传和视图不工作在MVC

文件上传:-我正在向您展示一个示例如何为上传文件编写代码

假设我在视频表中上传文件并使用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();
    }