Multiple Image File Upload with Captions

早过忘川 提交于 2019-12-23 18:39:28

问题


I managed to get the captions by foreach loop but now I'm facing a new problem.

I get duplicates in my database because of the nested loop, please check the code below.

JavaScript

window.onload = function () {
    if (window.File && window.FileList && window.FileReader) {
        var filesInput = document.getElementById("galleryFilesAdd");
        filesInput.addEventListener("change", function (event) {
            var files = event.target.files; //FileList object
            var output = document.getElementById("result");
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                if (!file.type.match('image'))
                    continue;
                var picReader = new FileReader();
                picReader.addEventListener("load", function (event) {
                    var picFile = event.target;
                    var div = document.createElement("div");
                    div.innerHTML = "<img class='thumbnail img-responsive' alt='" + picFile.name + "' + height='220' width='300'; src='" + picFile.result + "'" +
                            "title='" + picFile.name + "'/><button type='button' class='delete btn btn-default' class='remove_pic'> <span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button><input type='text' id ='imagecaption[]' name='imagecaption[]' class='form-control' placeholder='Add Image Caption'>"
                    output.insertBefore(div, null);
                    div.children[1].addEventListener("click", function (event) {
                        div.parentNode.removeChild(div);
                    });
                });
                //Read the image
                picReader.readAsDataURL(file);
            }
        });
    }
    else {
        console.log("Your browser does not support File API");
    }
}

Controller

public async Task<ActionResult> AddHotel(HotelViewModels.AddHotel viewModel, IEnumerable<HttpPostedFileBase> galleryFilesAdd)
{
    try
    {
        if (ModelState.IsValid)
        {

            foreach (var files in galleryFilesAdd)
            {
                var fileName = Guid.NewGuid().ToString("N");
                var extension = Path.GetExtension(files.FileName).ToLower();
                string thumbpath, imagepath = "";
                using (var img = Image.FromStream(files.InputStream))
                {
                  foreach (var caption in viewModel.imagecaption)
                  {
                    var galleryImg = new hotel_gallery_image
                    {
                        hotel_id = hotel.id,
                        thumbPath = String.Format("/Resources/Images/Hotel/GalleryThumb/{0}{1}", fileName, extension),
                        imagePath = String.Format("/Resources/Images/Hotel/Gallery/{0}{1}", fileName, extension),
                        entry_datetime = DateTime.Now,
                        guid = Guid.NewGuid().ToString("N"),
                        enabled = true,
                        image_caption = caption
                    };
                    db.hotel_gallery_image.Add(galleryImg);
                }
            }
          }

            await db.SaveChangesAsync();
            return RedirectToAction("Index", "Hotel");
        }
    }
    catch (DbEntityValidationException ex)
    {
        string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.PropertyName + ": " + x.ErrorMessage));
        throw new DbEntityValidationException(errorMessages);
    }
    viewModel.Country = await db.countries.ToListAsync();
    return View(viewModel);
}

and viewModel

public string[] imagecaption { get; set; }

Inserted data into database


回答1:


I think the problem is in your

image_caption = viewModel.imagecaption

because you iterate through var files in galleryFilesAddyou use the reference to the same image_caption from viewModel on each iteration, so you need to filter your image_caption depending on another data (fileName or another data which you viewmodel contains).

UPDATE Ideally if you have same properties in your ViewModel and files(filename for example), then you could do something like thatimage_caption = viewModel.FirstOrDefault(x=>x.Filename == filename).imagecaption

In order to be more specific would be helpful if you provide code for your Viemodel and galleryFilesAdd classes.

UPDATE 2

In your case 2nd foreach you iterate through whole collection of imagecaption array, on each iteration through galleryFilesAdd collection, which cause double data in you database. If you can take your captions sequentially for the 1st file take the 1st element from imagecaption array and so on then you can use code like this:

if (ModelState.IsValid)
        {
            int index = 0;
            foreach (var files in galleryFilesAdd)
            {
                var fileName = Guid.NewGuid().ToString("N");
                var extension = Path.GetExtension(files.FileName).ToLower();
                string thumbpath, imagepath = "";
                using (var img = Image.FromStream(files.InputStream))
                {
                 if(index < viewModel.imagecaption.Length){
                    var galleryImg = new hotel_gallery_image
                    {
                        hotel_id = hotel.id,
                        thumbPath = String.Format("/Resources/Images/Hotel/GalleryThumb/{0}{1}", fileName, extension),
                        imagePath = String.Format("/Resources/Images/Hotel/Gallery/{0}{1}", fileName, extension),
                        entry_datetime = DateTime.Now,
                        guid = Guid.NewGuid().ToString("N"),
                        enabled = true,
                        image_caption = viewModel.imagecaption[index]
                    };
                    db.hotel_gallery_image.Add(galleryImg);
                    index++;
                   }
            }
          }


来源:https://stackoverflow.com/questions/33590177/multiple-image-file-upload-with-captions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!