2015-11-08 53 views
3

我设法通过foreach循环获得标题,但现在我正面临一个新问题。多个图像文件上传带字幕

由于嵌套循环,我在我的数据库中得到了重复项,请检查下面的代码。

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

插入数据到数据库

enter image description here

+0

任何帮助家伙?谢谢 – Nevi

回答

0

我认为这个问题是在你的

image_caption = viewModel.imagecaption 

,因为你通过var files in galleryFilesAdd迭代你viewModel在每次迭代使用参照相同image_caption,所以您需要image_caption取决于过滤另一个数据(文件名或其他数据,你viewmodel包含)。

UPDATE 理想的情况下,如果你在你的视图模型和文件(文件名举例)相同的属性,那么你可以做这样的事情thatimage_caption = viewModel.FirstOrDefault(x=>x.Filename == filename).imagecaption

为了更具体,如果你提供的代码将是有益的你的ViemodelgalleryFilesAdd类。

更新2

你的情况,第二你的foreach通过整个收集imagecaption阵列的迭代,通过galleryFilesAdd收集每次迭代,这在你的数据库造成双数据。 如果你可以把字幕的顺序为1号文件采取从imagecaption数组的第1个要素等等,那么你可以使用这样的代码:

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

嗨那里如何过滤图像标题取决于我上传的文件? – Nevi

+0

我试图让我的imagecaption私人字符串[] imagecaption然后使用foreach循环来更新图像标题 – Nevi

+0

@Nevi请尝试从更新2代码 – user2771704