Home > Software engineering >  How to upload multiple images in database in ASP.NET Core MVC using ADO.NET
How to upload multiple images in database in ASP.NET Core MVC using ADO.NET

Time:11-03

I create a form where I upload images in database with their individual property. I am using ASP.NET Core MVC and ADO.NET, but now I want to upload multiple images with a single click.

Any idea how to upload multiple images? I want to add all images url into one property then save it into database.

Controller:

public IActionResult aprent([Bind] RentModel ar, [FromForm] string value)
{
    try
    {
        if (ModelState.IsValid)
        {
            if (ar.imge1 != null)
            {
                string folder = "image/";
                folder  = Guid.NewGuid().ToString()   "_"   ar.imge1.FileName ;
                ar.pic1 = "/"   folder;

                string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
                ar.imge1.CopyTo(new FileStream(serverFolder, FileMode.Create));
            }

            if (ar.imge2 != null)
            {
                string folder = "image/";
                folder  = Guid.NewGuid().ToString()   "_"   ar.imge2.FileName;

                ar.pic2 = "/"   folder;
                string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
                ar.imge2.CopyTo(new FileStream(serverFolder, FileMode.Create));
            }

            string res = DB.Saverecord(ar);
            string pics = DB.imagedb(ar);

            TempData["msg"] = res;
        }
    }
    catch (Exception ex)
    {
        TempData["msg"] = ex.Message;
    }

    return View();
}

Model:

public IFormFile imge1 { get; set; }
public string? pic2 { get; set; }
public IFormFile? imge2 { get; set; }

Class in which SQL queries are contained:

public string imagedb(RentModel img)
{
    try
    {
        con.Open();

        SqlCommand cmd = new SqlCommand("INSERT INTO img (pic1, pic2, pic3, pic4, pic5 /*,pic6, pic7, pic8, pic9, pic10*/) VALUES (@pic1, @pic2, @pic3, @pic4, @pic5 /*@pic6, @pic7, @pic8, @pic9, @pic10*/)", con);

        cmd.Parameters.AddWithValue("@pic1", img.pic1);
        cmd.Parameters.AddWithValue("@pic2", img.pic2);

        cmd.ExecuteNonQuery();

        con.Close();

        return "ok";
    }
    catch (Exception ex)
    {
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }

        return ex.Message.ToString();
    }
}

CodePudding user response:

It looks like you are storing your images in wwwroot.

  1. Maybe you want to save the same batch of uploaded image paths in some field in your database. You can add image paths one by one in the corresponding fields, and separate them with commas or other symbols, so as to ensure that the multiple images you upload at the same time can be stored in the same database data.

  2. Another way is adding another table related to the table(one to many relationships) eg GetImages table with imageurl property, copy the uploaded files to a folder of your choice and update the imageurl(s) of GetImages with strings pointing to the folder with images.

    Please refer to this link: How to map database relationships.

  3. If you want to store the image directly in the database, you can consider the FileUpload control, refer to this link.

Note that either way you use your database table structure is extremely important.So it is recommended that you add a new class and use the IFormFileCollection type and the multiple property to upload multiple images at the same time.

For example:

Model:

public class YourModel
{
    public IFormFileCollection Images { get; set; }
} 

Controller:

[HttpPost]
public IActionResult UploadImages(YourModel model)
{
    //Use a for loop to store the image and add the corresponding path to the database field
}

View:

@model YourModel

<form asp-controller="controller" asp-action="action" enctype="multipart/form-data" method="post">
    <input asp-for="@Model.Images" type="file" multiple />
    <input type="submit" value="Upload"/>
</form>

Hope this can help you.

Update:

I found a jquery plugin that can achieve your requirement.

Add the necessary library files to your project:

<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script>
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet" />

View:

<form id="UploadImages" enctype="multipart/form-data">
    <input type="file" id="Images" multiple />
    <input value="Upload" type="submit" />
</form>
<script>
        var pond = FilePond.create(document.querySelector('#Images'), {allowMultiple: true});
        $("#UploadImages").submit(function (e) {
            e.preventDefault();
            var formdata = new FormData();
            pondFiles = pond.getFiles();
            for (var i = 0; i < pondFiles.length; i  ) {
                formdata.append('Images', pondFiles[i].file);
            }

            $.ajax({
                method: "post",
                url: "/Home/Upload",
                data: formdata,
                processData: false,
                contentType: false
            });
        })
</script>

Controller:

[HttpPost]
public IActionResult Upload(IFormFile[] Images)
{
    return View();
}

This way you can pass it as an extra parameter to the controller without adding a new class or property. You can have a try.

  • Related