当前位置:Gxlcms > asp.net > ASP.NET MVC4使用MongoDB制作相册管理

ASP.NET MVC4使用MongoDB制作相册管理

时间:2021-07-01 10:21:17 帮助过:9人阅读

ASP.NET MVC4使用MongoDB制作相册管理实例分享

TIPS:1.Image转成Base64保存到mongodb字段
         2.数据模型是嵌套的关联 

首先定义Model层: 

  1. public class Photo : IEquatable<Photo>
  2. {
  3. [Required]
  4. public string PhotoName { get; set; }
  5. [Required]
  6. public string PhotoDescription { get; set; }
  7. public string ServerPath { get; set; }
  8. public Photo() { }
  9. public Photo(string name, string desc)
  10. {
  11. PhotoName = name;
  12. PhotoDescription = desc;
  13. }
  14. public bool Equals(Photo other)
  15. {
  16. return string.Equals(PhotoName, other.PhotoName);
  17. }
  18. }
  19. public interface IAlbumIterable
  20. {
  21. bool HasNext();
  22. Photo Current();
  23. Photo Next();
  24. }
  25. public interface IPhotosAggregable
  26. {
  27. IAlbumIterable GetIterator();
  28. }
  29. public class AlbumIterator : IAlbumIterable
  30. {
  31. private Album collection;
  32. private int count;
  33. public AlbumIterator(Album album)
  34. {
  35. collection = album;
  36. }
  37. public Photo Current()
  38. {
  39. if (count < collection.Count)
  40. return collection[count++];
  41. else
  42. throw new IndexOutOfRangeException();
  43. }
  44. public bool HasNext()
  45. {
  46. if (count < collection.Count - 1)
  47. return true;
  48. else
  49. return false;
  50. }
  51. public Photo Next()
  52. {
  53. if (HasNext())
  54. return collection[++count];
  55. else
  56. throw new IndexOutOfRangeException();
  57. }
  58. }
  59. public class Album : IPhotosAggregable
  60. {
  61. [BsonId]
  62. public ObjectId Id { get; set; }
  63. [Required]
  64. public string Name { get; set; }
  65. [Required]
  66. public string Description { get; set; }
  67. public string Owner { get; set; }
  68. public Photo TitlePhoto { get; set; }
  69. [BsonDateTimeOptions(Kind = DateTimeKind.Local,Representation =BsonType.DateTime)]
  70. public DateTime CreationTime { get; set; }
  71. public IList<Photo> Pictures { get; set; }
  72. public Album() { Pictures = new List<Photo>(); TitlePhoto = new Photo(); }
  73. public Album(string name, string owner, Photo pic)
  74. {
  75. Name = name;
  76. Owner = owner;
  77. TitlePhoto = pic;
  78. Pictures = new List<Photo>();
  79. TitlePhoto = new Photo();
  80. }
  81. public bool InsertPicture(Photo pic)
  82. {
  83. if (!Pictures.Contains(pic))
  84. {
  85. Pictures.Add(pic);
  86. return true;
  87. }
  88. else
  89. throw new ArgumentException();
  90. }
  91. public bool InsertPictures(List<Photo> photos)
  92. {
  93. foreach(var photo in photos)
  94. {
  95. if (!Pictures.Contains(photo))
  96. {
  97. Pictures.Add(photo);
  98. }
  99. else
  100. throw new ArgumentException();
  101. }
  102. return true;
  103. }
  104. public bool RemovePicture(Photo pic)
  105. {
  106. Pictures.Remove(pic);
  107. return true;
  108. }
  109. public int Count
  110. {
  111. get { return Pictures.Count; }
  112. }
  113. public Photo this[int index]
  114. {
  115. get { return Pictures[index]; }
  116. set { Pictures[index] = value; }
  117. }
  118. public IAlbumIterable GetIterator()
  119. {
  120. return new AlbumIterator(this);
  121. }
  122. }

 Services层的MongoAlbumPerformer.cs和ServerPathFinder.cs代码如下: 

  1. public class MongoAlbumPerformer
  2. {
  3. protected static IMongoClient client;
  4. protected static IMongoDatabase database;
  5. private static IMongoCollection<Album> collection;
  6. private string collectionName;
  7. public MongoAlbumPerformer(string databaseName, string collectionName)
  8. {
  9. client = new MongoClient(ConfigurationManager.ConnectionStrings["mongoDB"].ConnectionString);
  10. database = client.GetDatabase(databaseName);
  11. this.collectionName = collectionName;
  12. collection = database.GetCollection<Album>(collectionName, new MongoCollectionSettings { AssignIdOnInsert = true });
  13. }
  14. public void SetCollection(string collectionName)
  15. {
  16. this.collectionName = collectionName;
  17. collection = database.GetCollection<Album>(collectionName);
  18. }
  19. public void CreateAlbum(Album album)
  20. {
  21. var document = new Album
  22. {
  23. Name = album.Name,
  24. Owner = HttpContext.Current.User.Identity.Name,
  25. Description = album.Description,
  26. CreationTime = DateTime.Now,
  27. TitlePhoto = album.TitlePhoto,
  28. Pictures = album.Pictures
  29. };
  30. collection.InsertOne(document);
  31. }
  32. public List<Album> GetAlbumsByUserName(string username)
  33. {
  34. var projection = Builders<Album>.Projection
  35. .Include(a => a.Name)
  36. .Include(a => a.Description)
  37. .Include(a => a.TitlePhoto)
  38. .Include(a=>a.CreationTime);
  39. var result = collection
  40. .Find(a => a.Owner == HttpContext.Current.User.Identity.Name)
  41. .Project<Album>(projection).ToList();
  42. return result;
  43. }
  44. public Album GetPicturesByAlbumName(string albumName)
  45. {
  46. var projection = Builders<Album>.Projection
  47. .Include(a => a.Pictures);
  48. var result = collection
  49. .Find(a => a.Owner == HttpContext.Current.User.Identity.Name & a.Name == albumName)
  50. .Project<Album>(projection).FirstOrDefault();
  51. return result;
  52. }
  53. public void UpdateAlbumAddPhoto(string albumName, Photo photo)
  54. {
  55. var builder = Builders<Album>.Filter;
  56. var filter = builder.Eq(f => f.Name, albumName) & builder.Eq(f => f.Owner, HttpContext.Current.User.Identity.Name);
  57. var result = collection.Find(filter).FirstOrDefault();
  58. if (result == null)
  59. throw new ArgumentException("No album of supplied name: {0}", albumName);
  60. else
  61. {
  62. var picture = new Photo
  63. {
  64. PhotoName = photo.PhotoName,
  65. PhotoDescription = photo.PhotoDescription,
  66. ServerPath = photo.ServerPath,
  67. };
  68. var update = Builders<Album>.Update.Push(a => a.Pictures, picture);
  69. collection.UpdateOne(filter, update, new UpdateOptions { IsUpsert=true });
  70. }
  71. }
  72. public void DeletePhotoFromAlbum(string albumName, string photoName)
  73. {
  74. var builder = Builders<Album>.Filter;
  75. var filter = builder.Eq(f => f.Name, albumName) & builder.Eq(f => f.Owner, HttpContext.Current.User.Identity.Name);
  76. var result = collection.Find(filter).SingleOrDefault();
  77. if (result == null)
  78. throw new ArgumentException("No album of supplied name: {0}", albumName);
  79. else
  80. {
  81. var update = Builders<Album>.Update
  82. .PullFilter(a => a.Pictures, Builders<Photo>.Filter.Eq(p => p.PhotoName, photoName));
  83. long count = collection.UpdateOne(filter, update).MatchedCount;
  84. }
  85. }
  86. }public class ServerPathFinder
  87. {
  88. public string GetBase64ImageString(HttpPostedFileBase file)
  89. {
  90. string mime = Regex.Match(file.ContentType, @"(?<=image/)\w+").Value;
  91. byte[] bytes = new byte[file.ContentLength];
  92. file.InputStream.Read(bytes, 0, file.ContentLength);
  93. return string.Format("data:image/{0};base64,{1}",mime, Convert.ToBase64String(bytes));
  94. }
  95. }

AlbumController.cs代码如下: 

  1. public class AlbumController : Controller
  2. {
  3. MongoAlbumPerformer mongod = new MongoAlbumPerformer("test","albums");
  4. [HttpPost]
  5. public ActionResult AlbumPreview(Photo model, HttpPostedFileBase file, string albumName, string delete, string phot)
  6. {
  7. if (delete == "false")
  8. {
  9. if (file != null)
  10. {
  11. if (!file.ContentType.StartsWith("image"))
  12. {
  13. ModelState.AddModelError("file", "选择正确的格式照片!");
  14. }
  15. else
  16. {
  17. ServerPathFinder finder = new ServerPathFinder();
  18. model.ServerPath = finder.GetBase64ImageString(file);
  19. }
  20. if (ModelState.IsValid)
  21. {
  22. mongod.UpdateAlbumAddPhoto(albumName, model);
  23. ModelState.Clear();
  24. }
  25. }
  26. }
  27. else
  28. {
  29. mongod.DeletePhotoFromAlbum(albumName, phot);
  30. foreach(var error in ModelState.Values)
  31. {
  32. error.Errors.Clear();
  33. }
  34. }
  35. ViewBag.AlbumTitle = albumName;
  36. ViewBag.PhotoList = mongod.GetPicturesByAlbumName(albumName).Pictures;
  37. return View();
  38. }
  39. public ActionResult AlbumPreview(string Name)
  40. {
  41. var album = mongod.GetPicturesByAlbumName(Name);
  42. ViewBag.AlbumTitle = Name;
  43. ViewBag.PhotoList = album.Pictures;
  44. return View();
  45. }
  46. [HttpPost]
  47. public ActionResult Create(Album model, HttpPostedFileBase file)
  48. {
  49. if (!file.ContentType.StartsWith("image"))
  50. {
  51. ModelState.AddModelError("file", "选择正确的格式照片!");
  52. }
  53. else
  54. {
  55. ServerPathFinder finder = new ServerPathFinder();
  56. model.TitlePhoto.ServerPath = finder.GetBase64ImageString(file);
  57. }
  58. if (ModelState.IsValid)
  59. {
  60. model.Owner = HttpContext.User.Identity.Name;
  61. mongod.CreateAlbum(model);
  62. }
  63. var albums = mongod.GetAlbumsByUserName(HttpContext.User.Identity.Name);
  64. ViewBag.Albums = albums;
  65. return View();
  66. }
  67. public ActionResult Create()
  68. {
  69. var albums = mongod.GetAlbumsByUserName(HttpContext.User.Identity.Name);
  70. ViewBag.Albums = albums;
  71. return View();
  72. }
  73. }

部分view视图:
 Create.cshtml 

  1. @{
  2. ViewBag.Title = "Create";
  3. }
  4. <h2>我的相册</h2>
  5. @Html.Partial("_MyAlbums", (List<Album>)ViewBag.Albums)
  6. @using (Html.BeginForm("Create", "Album", FormMethod.Post, new { enctype = "multipart/form-data" }))
  7. {
  8. @Html.AntiForgeryToken()
  9. <div class="form-horizontal">
  10. <h4>创建新相册: </h4>
  11. <hr />
  12. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  13. <div class="form-group">
  14. @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
  15. <div class="col-md-10">
  16. @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
  17. @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
  18. </div>
  19. </div>
  20. <div class="form-group">
  21. @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
  22. <div class="col-md-10">
  23. @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
  24. @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
  25. </div>
  26. </div>
  27. <div class="form-group">
  28. @Html.LabelFor(model => model.TitlePhoto, htmlAttributes: new { @class = "control-label col-md-2" })
  29. <div class="col-md-10">
  30. <input type="file" name="file" id="file" style="width: 100%;" data-val="true" data-val-required="要求标题图片."/>
  31. @Html.ValidationMessage("file",new { @class = "text-danger" })
  32. </div>
  33. </div>
  34. <div class="form-group">
  35. <div class="col-md-offset-2 col-md-10">
  36. <input type="submit" value="Create" class="btn btn-default" />
  37. </div>
  38. </div>
  39. </div>
  40. }
  41. @section scripts{
  42. @Scripts.Render("~/bundles/jqueryval")
  43. <script type="text/javascript">
  44. $('img').click(function (data) {
  45. });
  46. </script>
  47. }AlbumPreview.cshtml
  48. @{
  49. ViewBag.Title = "AlbumPreview";
  50. }
  51. @using (Html.BeginForm("AlbumPreview", "Album", FormMethod.Post, new { enctype = "multipart/form-data"}))
  52. {
  53. @Html.AntiForgeryToken()
  54. {Html.RenderPartial("_Preview", (List<Photo>)ViewBag.PhotoList);}
  55. <div class="form-horizontal">
  56. <br />
  57. <h4>添加新的照片:</h4>
  58. <hr />
  59. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  60. <div class="form-group">
  61. @Html.LabelFor(model => model.PhotoName, htmlAttributes: new { @class = "control-label col-md-2" })
  62. <div class="col-md-10">
  63. @Html.EditorFor(model => model.PhotoName, new { htmlAttributes = new { @class = "form-control" } })
  64. @Html.ValidationMessageFor(model => model.PhotoName, "", new { @class = "text-danger" })
  65. </div>
  66. </div>
  67. <div class="form-group">
  68. @Html.LabelFor(model => model.PhotoDescription, htmlAttributes: new { @class = "control-label col-md-2" })
  69. <div class="col-md-10">
  70. @Html.EditorFor(model => model.PhotoDescription, new { htmlAttributes = new { @class = "form-control" } })
  71. @Html.ValidationMessageFor(model => model.PhotoDescription, "", new { @class = "text-danger" })
  72. </div>
  73. </div>
  74. <div class="form-group">
  75. <label class="control-label col-md-2">选择照片:</label>
  76. <div class="col-md-10">
  77. <input type="file" name="file" id="file" style="width: 100%;" data-val="true" data-val-required="请选择图像" />
  78. @Html.ValidationMessage("file", new { @class = "text-danger" })
  79. </div>
  80. </div>
  81. <div class="form-group">
  82. <div class="col-md-offset-2 col-md-10">
  83. <input type="submit" value="Create" class="btn btn-default" />
  84. </div>
  85. </div>
  86. </div>
  87. <input type="hidden" name="albumName" id="albumName" value="@ViewBag.AlbumTitle" />
  88. <input type="hidden" name="delete" id="delete" value="false" />
  89. <input type="hidden" name="phot" id="phot" value="sraka" />
  90. }
  91. @section scripts{
  92. @Scripts.Render("~/bundles/jqueryval")
  93. <script type="text/javascript">
  94. $(document).ready(function () {
  95. var elements = document.getElementsByClassName("btn btn-xs btn-warning cancel");
  96. for (var i = 0, len = elements.length; i < len; i++) {
  97. elements[i].addEventListener("click", function () {
  98. $('#delete').val(true);
  99. var name = $(this).attr("id");
  100. $('#phot').val(name);
  101. $('#' + name).click();
  102. });
  103. }
  104. })
  105. </script>
  106. }_Preview.cshtml
  107. @{
  108. ViewBag.Title = "_Preview";
  109. }
  110. <h2>Album <span style="color:royalblue;font-style:italic">@ViewBag.AlbumTitle</span></h2>
  111. <div class="row">
  112. @foreach (var photo in Model)
  113. {
  114. <div class="col-md-3">
  115. <input type="submit" id="@photo.PhotoName" value="删除" class="btn btn-xs btn-warning cancel" style="text-align:center;float:right" />
  116. <img src="@photo.ServerPath" class="img-responsive img-thumbnail col-md-3" style="width:100%;height:180px" />
  117. <label style="text-align:center;width:100%">@Html.DisplayNameFor(phot=>phot.PhotoName): @photo.PhotoName</label>
  118. <label style="text-align:center;width:100%;font-weight:100">@photo.PhotoDescription</label>
  119. </div>
  120. }
  121. </div>

运行项目结果如图:

首页创建相册:


《车》相册下的图片示例,可以增加图片,删除图片


《QQ》相册下的图片示例


mongodb数据存储结构图:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行