Alexis Mateo
Alexis Mateo

Reputation: 57

how can i save more than one image in the database?

I just want to save the route of the images in the database. So i try this.

And i get this error System.NullReferenceException: Object reference not set to an instance of an object.

This is my Controller

public ActionResult SaveImages(IEnumerable<HttpPostedFileBase> img, Imagenes images)
    {
        foreach (var n in img)
        {
            var PhotoUrl = Server.MapPath("/images" + n.FileName);
            if (n != null && n.ContentLength > 0)
                n.SaveAs(PhotoUrl);
            images.imgUrl = "/images" + n.FileName;

            db.Imagenes.Add(images);
            db.SaveChanges();
        }
        return View("Index");

    }

This is my model class

    public partial class Imagenes
{
    public int id { get; set; }

    [StringLength(200)]
    public string imgUrl { get; set; }
}

my View

@{
ViewBag.Title = "Home Page";}

@using (Html.BeginForm("SaveImages", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
    <input type="file" name="img" id="img" multiple />
    <input type="submit" name="submit" value="Save"/>
</div>}

Upvotes: 2

Views: 577

Answers (1)

balexandre
balexandre

Reputation: 75093

The error you are getting is nothing about the image saving part, but I'm assuming it's the use of your images property...

As you didn't specify where that property comes from, MVC automatically assumes that's a POST Variable, and in your HTML, you have nothing of sorts...

change your action code to:

public ActionResult SaveImages(IEnumerable<HttpPostedFileBase> img)
{
    const string folderToUpload = "/images";

    foreach (var n in img)
    {
        var imageToUpload = folderToUpload + n.FileName;
        var photoUrl = Server.MapPath(imageToUpload);

        if (n != null && n.ContentLength > 0) {

            n.SaveAs(photoUrl);      // save to folder

            var images = new Imagenes {
               imgUrl = imageToUpload
            };

            db.Imagenes.Add(images); // add to repository
            db.SaveChanges();        // save repositorychanges
        }
    }

    return redirectToAction("Index");
}

I'm also assuming that db was already injected in your constructor, and it's not NULL

Code edited:

  • create a constant variable to have the folder to upload, so you don't repeat that code over and over
  • create a variable to hold the full path of the image, so you don't repeat that code over and over (remember: DRY - Don't Repeat Yourself)

  • save to database only if the file was saved

  • create a new variable to hold your object to be saved
  • redirect to the action using redirectToAction as you might have some calls in your Index and only redirecting to the View would give you an error
  • to be persistence, change the PhotoUrl to photoUrl (local variables = start with lowercase)

Upvotes: 2

Related Questions