【MVC】快速构建一个图片浏览网站

引言

     当抄完MusicStore时,你应该对MVC有一个比较清晰的认识了.接下来就需要做个网站来继续增加自己的知识了.那么,该做个什么网站呢.做个图片浏览网站吧,简单而实用.

简单设计

    1.首先,页面中间是个图片列表.将所有图片列出来是不太科学的,所以要做个分页浏览的功能.

    2.页面右边,有个图片排行榜,列出点击量前10名的图片名称.而且,同一时间段同一客户端的重复点击只能计算一次才合理的.

    3.有图片浏览就肯定有图片上传功能啦,还必须要是登录后才能上传.

数据层

    采用EF的Code First方式构建数据库,先定义一个ImageModle,放到DbContext数据上下文中,再定义一个DropCreateDatabaseIfModelChanges迁移类,在seed方法中初始化数据,如下

    public class ImageModle
    {
        [Display(Name="编号")]
        public int Id { get; set; }
        [Display(Name="图片名")]
        public string ImageName { get; set; }
        [Display(Name = "图片相对路径")]
        public string ImageUrl { get; set; }
        [Display(Name = "上传者")]
        public string Uploader { get; set; }
        [Display(Name = "点击数")]
        public int HitCount { get; set; }
        [Display(Name = "上传时间")]
        public DateTime UploadDateTime { get; set; }     
    }

    public class ImageMangeEntities:DbContext
    {
        public ImageMangeEntities()
            : base("DefaultConnection")
        {
        }
        public DbSet<ImageModle> Images { get; set; }
    }

 public class ImageData : DropCreateDatabaseIfModelChanges<ImageMangeEntities>
    {
        protected override void Seed(ImageMangeEntities context)
        {
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/9662C9V1UU02.jpg", ImageName = "图片1", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698710MJjSR8.jpg", ImageName = "图片2", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698710MJjSR8.jpg", ImageName = "图片3", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/9662C9V1UU02.jpg", ImageName = "图片4", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698710MJjSR8.jpg", ImageName = "图片5", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/9662C9V1UU02.jpg", ImageName = "图片6", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698710MJjSR8.jpg", ImageName = "图片7", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698710MJjSR8.jpg", ImageName = "图片8", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/9662C9V1UU02.jpg", ImageName = "图片9", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698713w8Epfw.jpg", ImageName = "图片10", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698710MJjSR8.jpg", ImageName = "图片11", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/9662C9V1UU02.jpg", ImageName = "图片12", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/9662C9V1UU02.jpg", ImageName = "图片13", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698713w8Epfw.jpg", ImageName = "图片14", HitCount = 1, UploadDateTime = DateTime.Now });
            context.Images.Add(new ImageModle() { ImageUrl = "~/Images/1343698713w8Epfw.jpg", ImageName = "图片15", HitCount = 1, UploadDateTime = DateTime.Now });
            context.SaveChanges();
        }
    }

主页

     主页的构成很简单,中间是个ul列表,右边是点击排行榜,分页主要是利用PagedListPager扩展方法,View和Control如下

ImageMangeEntities ImageDB = new ImageMangeEntities();

        public ActionResult Index(int? page)
        {
            List<ImageModle> model = new List<ImageModle>();
            model = ImageDB.Images.ToList();
            int pagenumber = page ?? 1;
            var retmodel = model.ToPagedList(pagenumber, 12);
            return View(retmodel);
        }
@model IPagedList<MusicStoreTest.Models.ImageModle>
@{
ViewBag.Title = "主页";
}
@using PagedList;
@using PagedList.Mvc;
<h2>图片浏览</h2>

<div style="float: left;">
    <ul id="album-list">
        @foreach (var item in Model)
        {
            <li><a href="@Url.Action("Details", "Image",
                             new {id = item.Id})">

                    <img style="width: 100px; height: 100px" alt="@item.ImageName" src="@Url.Content(@item.ImageUrl)"/>
                    <span >@item.ImageName</span> </a>
            </li>
        }
    </ul>   
</div>
<div style="float:left;">
         @{Html.RenderAction("ImageHitList");}
</div>
 <div  style="vertical-align: middle; clear: both;margin-left: 50px">       
        @Html.PagedListPager((IPagedList) Model, page => Url.Action("Index", new {page = page}))
</div>

点击量计算实现
    要实现同一时间段内不算点击量累计,可以用HttpContext.Session实现,就定30分钟期限吧,30分钟内无操作就可以继续计算点击量,如下

         <sessionState timeout="30"/>
        public ActionResult Details(int id)
        {
            List<ImageModle> model = new List<ImageModle>();
            var item = ImageDB.Images.Find(id);
            var session = HttpContext.Session[id.ToString()];
            if (session == null)
            {
                HttpContext.Session[id.ToString()] = "browseId";
                item.HitCount = item.HitCount + 1;
                ImageDB.Entry(item).State = EntityState.Modified;           
                ImageDB.SaveChanges();
            }

            ViewBag.ImageName = item.ImageName;
            ViewBag.ImageUrl = item.ImageUrl;return View();
        }

上传图片
     还有上传图片功能,要加上[Authorize]特性实现登录后才能上传图片,如下

        [HttpPost]
        [Authorize]
        public JsonResult UploadImage(HttpPostedFileBase image)
        {
            if (image != null)
            {
                string guid =  Guid.NewGuid().ToString();
                string fileName = Path.GetFileName(image.FileName);
                string filePath = Path.Combine(Server.MapPath("~/Files"), guid + "-" + fileName);
                string clientPath = "/Files/" + guid + "-" + fileName;
                image.SaveAs(filePath);
                ImageModle imageModle = new ImageModle();
                imageModle.ImageName =  fileName;
                imageModle.ImageUrl = clientPath;
                imageModle.HitCount = 0;
                imageModle.Uploader = User.Identity.Name;
                imageModle.UploadDateTime=DateTime.Now;
                ImageDB.Images.Add(imageModle);
                ImageDB.SaveChanges();
                return Json(new { success = true, result = clientPath });
            }
            else
            {
                return Json(new { success = false, msg = "上传失败!" });
            }
        }

 

@{
    ViewBag.Title = "UploadImage";
}
<h2 id="ssss">上传图片</h2>
@using (Html.BeginForm("UploadImage", "Image", FormMethod.Post, new { enctype = "multipart/form-data", id = "ImageForm" }))
{
    <img  alt="请上传图片" id="img" width="800" height="500"/>
    <input type="file" id="imageInput" name="image" accept="image/gif,image/jpeg,image/png,gif|jpg|png"/>
    <input type="button" id="btn" value="提交"/>
    <span class="img-msg"></span>
}
@section Scripts {
    <script>
         
        $('#imageInput').change(function () {
            if ($(this).val().length > 0) {
                var file = this.files[0]; 
                var reader = new FileReader();
                reader.onload=function (e)
                {
                    $("#img").attr("src", e.target.result);
                }
                reader.readAsDataURL(file);
            }
        });
    
        $('#btn').click(function () {
            if ($("#imageInput").val().length > 0) {
                alert($("#imageInput").val());
                $('#ImageForm').ajaxSubmit({
                    dataType: 'json',
                    success: function (data) {
                        $('.img-msg').text("");
                        if (data.success) {
                            $("#img").attr("src", data.result);
                        } else {
                            alert(data.msg);
                        }
                    },
                    error: function () {
                        alert("上传失败");
                    },
                    beforeSend: function () {
                        $('.img-msg').text("正在上传,请稍后...");
                    }
                });
            }
        });
    </script>
}

 

小结

     做这么一个网站很简单,熟练的人大概半个小时就可以完成了,但这是入门的必修课.另外,当完成第一个网站时,你就会发现MVC之路才是刚刚开始.

posted @ 2015-07-03 23:31  Caizl  阅读(873)  评论(0编辑  收藏  举报