我收到错误#34; NullReferenceException未被用户代码"处理我尝试上传Image ASP.NET MVC 4

时间:2015-07-01 15:35:17

标签: c# asp.net asp.net-mvc asp.net-mvc-4 c#-4.0

的Controler

    [HttpPost]
    public ActionResult Index(Add_Book _books)
    {
        BusinessLayer booksBusinessLayer = new BusinessLayer();
        //books file = new books();
        //var book = new books();

在以下行接收错误

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

模态

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

请求提供解决方案。

1 个答案:

答案 0 :(得分:0)

就像David Tansey所说,_books.File.FileName假设它是非null,所以你需要先验证才能尝试访问该对象,

当我使用上传文件时,我做了类似下面的代码,希望这对你有帮助

只需在您的视图中使用

   <input type="file" />

然后在你的控制器中,在这种情况下我把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);
         }
     }