繁体   English   中英

文件上传和查看在MVC中不起作用

[英]File upload And View Not Working in MVC

我正在创建使用实体框架的MVC应用程序。 最后要创建File upload和View。 我有Controller Project Controller要上传文件

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

以前,此代码是在没有实体框架的情况下开发的。 采取这个创建的实体框架模型后,我看到了两个类的模型类型,我可以在模型文件夹下看到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

请有人告诉我我犯了什么错误? 请有人帮忙解决这个问题吗?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM