0

I new to MVC. I want to upload image path into the database. I refferd many tutorial. Most Of the tutorial says like

     [HttpPost]
        public ActionResult Index(FormCollection form, HttpPostedFileBase file)
        {
            var allowedExtensions = new[] {  
            ".Jpg", ".png", ".jpg", "jpeg"  
        };
            tblDemo tbl = new tblDemo();
            tbl.Photo = file.ToString(); //getting complete url  
            tbl.Name = form["Name"];
            var fileName = Path.GetFileName(file.FileName);
            var ext = Path.GetExtension(file.FileName);
            /..Remining code here../
}

but i am getting the error like Object reference not set to an instance of an object in file object (getting as file=NULL),I followed same like in many tutorial,all i am getting is same error. Then what is wrong with me? Give me please some solution for uploading image path into database and image to the folder (i don't want to save image to the database)

John Mathew
  • 41
  • 12
  • Your source code doesn't say too much. Where's database insertion code? Where are you getting exception? – Fka Oct 16 '15 at 06:21
  • i am getting the error in tbl.Photo = file.ToString(); – John Mathew Oct 16 '15 at 06:23
  • and the error is Object reference not set to an instance of an object. @Fka – John Mathew Oct 16 '15 at 06:23
  • I posted piece of my source code which is extremely simple. Are you sure file is uploaded? – Fka Oct 16 '15 at 06:28
  • Refer [uploading files with asp.net mvc](http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/). And `tbl.Photo = file.ToString()` makes no sense. You need to save the file first and then assign the path. –  Oct 16 '15 at 06:37
  • @Stephen Muecke : Thanks sir... Now its working as i am expected – John Mathew Oct 17 '15 at 09:30

1 Answers1

0

I use following code to upload a file:

model

public class Model
{
    ...

    public HttpPostedFileBase File { get; set; }
}

controller

public ActionResult SaveDetails(TargetGroupDetailModel model)
{
    if(model.File != null && model.File.ContentLength > 0)
    {
        string fileName = model.File.FileName;
        ....
    }
    ...
}
Fka
  • 6,044
  • 5
  • 42
  • 60