多图像文件上传与字幕 [英] Multiple Image File Upload with Captions

查看:126
本文介绍了多图像文件上传与字幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法通过的foreach 循环的字幕,但现在我面临着一个新的问题。

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

我得到重复我的数据库,因为嵌套循环,请检查下面的code。

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

JavaScript的

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");
    }
}

控制器

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);
}

和视图模型

public string[] imagecaption { get; set; }

插入的数据到数据库

Inserted data into database

推荐答案

我认为这个问题是在

image_caption = viewModel.imagecaption

因为你通过迭代在galleryFilesAdd var中的文件您使用引用相同的 image_caption 视图模型在每次迭代,所以你需要过滤 image_caption 根据另一个数据(文件名或其他数据,你视图模型包含)。

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).

更新
理想的情况是,如果你在你的视图模型和文件相同的属性(文件名,例如),那么你可以做类似 thatimage_caption = viewModel.FirstOrDefault(X =&GT; x.Filename ==文件名).imagecaption

为了更具体会是有益的,如果你提供code你的 Viemodel galleryFilesAdd 类。

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

更新2

在您完成的收集 imagecaption 阵列,通过每一次迭代 galleryFilesAdd 集合,它在你的数据库导致双数据。
如果你可以把字幕的顺序为1号文件从imagecaption阵列获取的第一个元素等等,那么你可以用code是这样的:

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++;
                   }
            }
          }

这篇关于多图像文件上传与字幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆