簡體   English   中英

當我嘗試上傳圖像 ASP.NET MVC 4 時,我收到“用戶代碼未處理 NullReferenceException”的錯誤

[英]I am getting error of "NullReferenceException was unhandled by user code" while i try to upload Image ASP.NET MVC 4

控制器

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

請提供解決方案。

就像 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);
         }
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM