[英]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.