[英]I am getting error of "NullReferenceException was unhandled by user code" while i try to upload Image ASP.NET MVC 4
Controler控制器
[HttpPost]
public ActionResult Index(Add_Book _books)
{
BusinessLayer booksBusinessLayer = new BusinessLayer();
//books file = new books();
//var book = new books();
receiving error at below line在下面的行接收错误
var fileName = Path.GetFileName(_books.File.FileName);
//var fileName = book.File.FileName;
var path = Path.Combine(Server.MapPath("~/Osho_Images"), fileName);
book.File.SaveAs(path);
booksBusinessLayer.AddBooks(_books);
return View();
}
Modal模态
public class books
{
public string ID
{
get;
set;
}
public string ISBN
{
get;
set;
}
public string Book_Title
{
get;
set;
}
public string Book_Cat
{
get;
set;
}
public string Language
{
get;
set;
}
public string Book_Desc
{
get;
set;
}
public string Price
{
get;
set;
}
public string Book_Img
{
get;
set;
}
public HttpPostedFileBase File
{
get;
set;
}
public int Qty
{
get;
set;
}
public int Qty_Alert
{
get;
set;
}
}
Pleas provide the solution.请提供解决方案。
Like David Tansey say, _books.File.FileName assume that is NOT null, so you need to validate before to try get access to the object,就像 David Tansey 说的,_books.File.FileName 假设它不是 null,所以你需要在尝试访问对象之前进行验证,
When I worked with upload files I did something like the following code, hope this help you当我处理上传文件时,我做了类似下面的代码,希望这对你有帮助
just use in your view仅在您的视图中使用
<input type="file" />
then in your controller, in this case i put the for, because the user can upload multiple files,然后在你的控制器中,在这种情况下,我把 for,因为用户可以上传多个文件,
[HttpPost]
public ActionResult SaveFile(YourModel model)
{
foreach (string file in Request.Files)
{
SaveYourFile(Request.Files[file]);
}
return View();
}
private void SaveYourFile(HttpPostedFileBase file)
{
if(file.ContentLenght >0)
{
//now you can access to your uploaded file
var book = new books();
var path = Path.Combine(Server.MapPath("~/Osho_Images"), file.fileName);
book.File.SaveAs(path);
booksBusinessLayer.AddBooks(_books);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.