0

I am trying to upload an image directly to my database. I am having an issue with an object reference not being set to an instance on an object.

First, I added a property to my model.

public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    ...

    public byte[] MainPhoto { get; set; }

    ...

}

I used Entity Framework to update my products table and everything is good there.

Then I used this method in my controller to write the bits into the db.

public ActionResult Create([Bind(Include = "ID,Title,Price,Description,Availability,Category,ApplicationUserID")] Product product, HttpPostedFileBase ImageFile)
{
  if (ModelState.IsValid)
  {
    db.Products.Add(product);
    var userID = User.Identity.GetUserId();
    product.ApplicationUserID = userID;

    using (var ms = new MemoryStream())
    {
      {
        ImageFile.InputStream.CopyTo(ms);
        product.MainPhoto = ms.ToArray();
      }
    }

    db.SaveChanges();
    return RedirectToAction("Index");
  }
  return View(product);

Finally, I just put this input in my HTML template.

<label for="ImageFile">Upload Image:</label>
<input name="ImageFile" type="file" />

I am getting an exception that reads:

"Object reference not set to an instance of an object."

That is throwing an exception on this line:

ImageFile.InputStream.CopyTo(ms);

It would seem that it is not recognizing the var ms as an instance of MemoryStream, but I'm not 100% sure. Thank you for any assistance!

Richard
  • 106,783
  • 21
  • 203
  • 265

0 Answers0