当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET MVC4使用MongoDB制作相册管理

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

伯爵卓尔,难舍难分歌词,陈良宇是谁的儿子

asp.net mvc4使用mongodb制作相册管理实例分享

tips:1.image转成base64保存到mongodb字段
         2.数据模型是嵌套的关联 

首先定义model层: 

 public class photo : iequatable<photo>
 {
  [required]
  public string photoname { get; set; }


  [required]
  public string photodescription { get; set; }


  public string serverpath { get; set; }


  public photo() { }


  public photo(string name, string desc)
  {
   photoname = name;
   photodescription = desc;
  }


  public bool equals(photo other)
  {
   return string.equals(photoname, other.photoname);
  }
 }
 
 
public interface ialbumiterable
 {
  bool hasnext();
  photo current();
  photo next();
 } 
 
 
 public interface iphotosaggregable
 {
  ialbumiterable getiterator();
 }


 public class albumiterator : ialbumiterable
 {
  private album collection;
  private int count;


  public albumiterator(album album)
  {
   collection = album;
  }


  public photo current()
  {
   if (count < collection.count)
    return collection[count++];
   else
    throw new indexoutofrangeexception();
  }


  public bool hasnext()
  {
   if (count < collection.count - 1)
    return true;
   else
    return false;
  }


  public photo next()
  {
   if (hasnext())
    return collection[++count];
   else
    throw new indexoutofrangeexception();
  }
 } 
 public class album : iphotosaggregable
 {
  [bsonid]
  public objectid id { get; set; }


  [required]
  public string name { get; set; }


  [required]
  public string description { get; set; }


  public string owner { get; set; }
  public photo titlephoto { get; set; }


  [bsondatetimeoptions(kind = datetimekind.local,representation =bsontype.datetime)]
  public datetime creationtime { get; set; }
  public ilist<photo> pictures { get; set; }


  public album() { pictures = new list<photo>(); titlephoto = new photo(); }
  public album(string name, string owner, photo pic)
  {
   name = name;
   owner = owner;
   titlephoto = pic;
   pictures = new list<photo>();
   titlephoto = new photo();
  }


  public bool insertpicture(photo pic)
  {
   if (!pictures.contains(pic))
   {
    pictures.add(pic);
    return true;
   }
   else
    throw new argumentexception();
  }


  public bool insertpictures(list<photo> photos)
  {
   foreach(var photo in photos)
   {
    if (!pictures.contains(photo))
    {
     pictures.add(photo);
    }
    else
     throw new argumentexception();
   }
   return true;
  }


  public bool removepicture(photo pic)
  {
    pictures.remove(pic);
    return true;
  }


  public int count
  {
   get { return pictures.count; }
  }


  public photo this[int index]
  {
   get { return pictures[index]; }
   set { pictures[index] = value; }
  }


  public ialbumiterable getiterator()
  {
   return new albumiterator(this);
  }
 }

 services层的mongoalbumperformer.cs和serverpathfinder.cs代码如下: 

 public class mongoalbumperformer
 {
  protected static imongoclient client;
  protected static imongodatabase database;
  private static imongocollection<album> collection;
  private string collectionname;

  public mongoalbumperformer(string databasename, string collectionname)
  {
   
   client = new mongoclient(configurationmanager.connectionstrings["mongodb"].connectionstring);
   database = client.getdatabase(databasename);
   this.collectionname = collectionname;
   collection = database.getcollection<album>(collectionname, new mongocollectionsettings { assignidoninsert = true });
  }

  public void setcollection(string collectionname)
  {
   this.collectionname = collectionname;
   collection = database.getcollection<album>(collectionname);
  }

  public void createalbum(album album)
  {
   var document = new album
   {
    name = album.name,
    owner = httpcontext.current.user.identity.name,
    description = album.description,
    creationtime = datetime.now,
    titlephoto = album.titlephoto,
    pictures = album.pictures
   };

   collection.insertone(document);
  }

  public list<album> getalbumsbyusername(string username)
  {
   var projection = builders<album>.projection
    .include(a => a.name)
    .include(a => a.description)
    .include(a => a.titlephoto)
    .include(a=>a.creationtime);

   var result = collection
    .find(a => a.owner == httpcontext.current.user.identity.name)
    .project<album>(projection).tolist();

   return result;
  }

  public album getpicturesbyalbumname(string albumname)
  {
   var projection = builders<album>.projection
    .include(a => a.pictures);

   var result = collection
    .find(a => a.owner == httpcontext.current.user.identity.name & a.name == albumname)
    .project<album>(projection).firstordefault();

   return result;
  }

  public void updatealbumaddphoto(string albumname, photo photo)
  {
   var builder = builders<album>.filter;
   var filter = builder.eq(f => f.name, albumname) & builder.eq(f => f.owner, httpcontext.current.user.identity.name);
   var result = collection.find(filter).firstordefault();

   if (result == null)
    throw new argumentexception("no album of supplied name: {0}", albumname);
   else
   {
      var picture = new photo
      {
       photoname = photo.photoname,
       photodescription = photo.photodescription,
       serverpath = photo.serverpath,
      };

      var update = builders<album>.update.push(a => a.pictures, picture);
      collection.updateone(filter, update, new updateoptions { isupsert=true });
   }
  }

  public void deletephotofromalbum(string albumname, string photoname)
  {
   var builder = builders<album>.filter;
   var filter = builder.eq(f => f.name, albumname) & builder.eq(f => f.owner, httpcontext.current.user.identity.name);
   var result = collection.find(filter).singleordefault();

   if (result == null)
    throw new argumentexception("no album of supplied name: {0}", albumname);
   else
   {
    var update = builders<album>.update
     .pullfilter(a => a.pictures, builders<photo>.filter.eq(p => p.photoname, photoname));
    long count = collection.updateone(filter, update).matchedcount;
   }
  }
 }public class serverpathfinder
 {
  public string getbase64imagestring(httppostedfilebase file)
  {
   string mime = regex.match(file.contenttype, @"(?<=image/)\w+").value;
   byte[] bytes = new byte[file.contentlength];
   file.inputstream.read(bytes, 0, file.contentlength);
   return string.format("data:image/{0};base64,{1}",mime, convert.tobase64string(bytes));
  }
 }

albumcontroller.cs代码如下: 

 public class albumcontroller : controller
 {
  mongoalbumperformer mongod = new mongoalbumperformer("test","albums");

  [httppost]
  public actionresult albumpreview(photo model, httppostedfilebase file, string albumname, string delete, string phot)
  {
   if (delete == "false")
   {
    if (file != null)
    {
     if (!file.contenttype.startswith("image"))
     {
      modelstate.addmodelerror("file", "选择正确的格式照片!");
     }
     else
     {
      serverpathfinder finder = new serverpathfinder();
      model.serverpath = finder.getbase64imagestring(file);
     }

     if (modelstate.isvalid)
     {
      mongod.updatealbumaddphoto(albumname, model);
      modelstate.clear();
     }
    }
   }
   else
   {
    mongod.deletephotofromalbum(albumname, phot);
    foreach(var error in modelstate.values)
    {
     error.errors.clear();
    }
   }
   viewbag.albumtitle = albumname;
   viewbag.photolist = mongod.getpicturesbyalbumname(albumname).pictures;

   return view();
  }

  public actionresult albumpreview(string name)
  {
   var album = mongod.getpicturesbyalbumname(name);
   viewbag.albumtitle = name;
   viewbag.photolist = album.pictures;

   return view();
  }

  [httppost]
  public actionresult create(album model, httppostedfilebase file)
  {
   if (!file.contenttype.startswith("image"))
   {
    modelstate.addmodelerror("file", "选择正确的格式照片!");
   }
   else
   {
    serverpathfinder finder = new serverpathfinder();
    model.titlephoto.serverpath = finder.getbase64imagestring(file);    
   }

   if (modelstate.isvalid)
   {
    model.owner = httpcontext.user.identity.name;
    mongod.createalbum(model);
   }
   var albums = mongod.getalbumsbyusername(httpcontext.user.identity.name);
   viewbag.albums = albums;

   return view();
  }

  public actionresult create()
  {
   var albums = mongod.getalbumsbyusername(httpcontext.user.identity.name);
   viewbag.albums = albums;
   return view();
  }
 } 

部分view视图:
 create.cshtml 

@{
 viewbag.title = "create";
}

<h2>我的相册</h2>

@html.partial("_myalbums", (list<album>)viewbag.albums)

@using (html.beginform("create", "album", formmethod.post, new { enctype = "multipart/form-data" })) 
{
 @html.antiforgerytoken()
 
 <div class="form-horizontal">
  <h4>创建新相册: </h4>
  <hr />
  @html.validationsummary(true, "", new { @class = "text-danger" })
  <div class="form-group">
   @html.labelfor(model => model.name, htmlattributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @html.editorfor(model => model.name, new { htmlattributes = new { @class = "form-control" } })
    @html.validationmessagefor(model => model.name, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @html.labelfor(model => model.description, htmlattributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @html.editorfor(model => model.description, new { htmlattributes = new { @class = "form-control" } })
    @html.validationmessagefor(model => model.description, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @html.labelfor(model => model.titlephoto, htmlattributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    <input type="file" name="file" id="file" style="width: 100%;" data-val="true" data-val-required="要求标题图片."/>
    @html.validationmessage("file",new { @class = "text-danger" })
   </div>
  </div>
  
  <div class="form-group">
   <div class="col-md-offset-2 col-md-10">
    <input type="submit" value="create" class="btn btn-default" />
   </div>
  </div>
 </div>
}

@section scripts{
 @scripts.render("~/bundles/jqueryval")

 <script type="text/javascript">
  $('img').click(function (data) {

  });

 </script>
}albumpreview.cshtml
 @{
 viewbag.title = "albumpreview";
}

@using (html.beginform("albumpreview", "album", formmethod.post, new { enctype = "multipart/form-data"}))
{
 @html.antiforgerytoken()

 {html.renderpartial("_preview", (list<photo>)viewbag.photolist);}

 <div class="form-horizontal">
  <br />
  <h4>添加新的照片:</h4>
  <hr />
  @html.validationsummary(true, "", new { @class = "text-danger" })

  <div class="form-group">
   @html.labelfor(model => model.photoname, htmlattributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @html.editorfor(model => model.photoname, new { htmlattributes = new { @class = "form-control" } })
    @html.validationmessagefor(model => model.photoname, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @html.labelfor(model => model.photodescription, htmlattributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @html.editorfor(model => model.photodescription, new { htmlattributes = new { @class = "form-control" } })
    @html.validationmessagefor(model => model.photodescription, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   <label class="control-label col-md-2">选择照片:</label>
   <div class="col-md-10">
    <input type="file" name="file" id="file" style="width: 100%;" data-val="true" data-val-required="请选择图像" />
    @html.validationmessage("file", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   <div class="col-md-offset-2 col-md-10">
    <input type="submit" value="create" class="btn btn-default" />
   </div>
  </div>
 </div>
 <input type="hidden" name="albumname" id="albumname" value="@viewbag.albumtitle" />
 <input type="hidden" name="delete" id="delete" value="false" />
 <input type="hidden" name="phot" id="phot" value="sraka" />
}

@section scripts{
 @scripts.render("~/bundles/jqueryval")

 <script type="text/javascript">
  $(document).ready(function () {
   var elements = document.getelementsbyclassname("btn btn-xs btn-warning cancel");
   for (var i = 0, len = elements.length; i < len; i++) {
    elements[i].addeventlistener("click", function () {
     $('#delete').val(true);
     var name = $(this).attr("id");
     $('#phot').val(name);
     $('#' + name).click();
    });
   }
  })
 </script>
}_preview.cshtml
 @{
 viewbag.title = "_preview";
}

<h2>album <span style="color:royalblue;font-style:italic">@viewbag.albumtitle</span></h2>

<div class="row">
@foreach (var photo in model)
{
 <div class="col-md-3">
  <input type="submit" id="@photo.photoname" value="删除" class="btn btn-xs btn-warning cancel" style="text-align:center;float:right" />
  <img src="@photo.serverpath" class="img-responsive img-thumbnail col-md-3" style="width:100%;height:180px" />
  <label style="text-align:center;width:100%">@html.displaynamefor(phot=>phot.photoname): @photo.photoname</label>
  <label style="text-align:center;width:100%;font-weight:100">@photo.photodescription</label>
 </div>
}
</div>

运行项目结果如图:

首页创建相册:


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


《qq》相册下的图片示例


mongodb数据存储结构图:


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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网