首页 > 代码库 > MVC图片上传并显示缩略图
MVC图片上传并显示缩略图
前面已经说了怎么通过MVC来上传文件,那么这次就说说如何上传图片然后显示缩略图,这个的实用性还是比较大。用UpLoad文件夹来保存上传的图片,而Temp文件夹来保存缩略图,前面文件上传部分就不再重复了,不过图片上传当然只能是图片格式的文件,因此在之前那篇博客中 通过控制格式的上传便能防止恶意上传,这个是文件上传的教程链接:http://www.cnblogs.com/xmfdsh/p/3988868.html
对于数据库的设计的话就随便点:
于是用EF便自动生成了类如下:
public partial class Image { public int Id { get; set; } public string ImgName { get; set; } public string ImgSize { get; set; } public System.DateTime UpLoadTime { get; set; } }
下面是缩略图产生的函数:
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace UpLoadImg.Utilities{ public class Thumbnail { public static void CreateThumbnail(string source,string destination,int maxWidth,int maxHeight) { System.Drawing.Image Img = System.Drawing.Image.FromFile(source); int Width = Img.Width; int Height = Img.Height; int thumbnailWidth, thumbnailHeight; Resize(Width, Height, maxWidth, maxHeight, out thumbnailWidth, out thumbnailHeight); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(thumbnailWidth, thumbnailHeight); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap); graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.DrawImage(Img, 0, 0, thumbnailWidth, thumbnailHeight); bitmap.Save(destination); } private static void Resize(int Width,int Height,int maxWidth,int maxHeight,out int sizedWidth,out int sizedHeight) { if(Width<maxWidth && Height<maxHeight) { sizedWidth=Width; sizedHeight=Height; return ; } sizedWidth = maxWidth; sizedHeight = (int)((double)Height / Width * sizedWidth + 0.5); if(sizedHeight>maxHeight) { sizedHeight = maxHeight; sizedWidth = (int)((double)Width / Height * sizedHeight + 0.5); } } }}
这种缩略图的函数网上一搜一大把,不过实现起来也不难,就像上面那样,我就不写注释,不过应该想看懂难度还是不大的。
先说上传的过程,和上次是一样的,只不过这次需要在数据库中保存一些数据,因此上传后到了服务端便要对数据进行存储处理:
[HttpPost] public ContentResult UpLoadFile(HttpPostedFileBase fileData) { if (fileData != null && fileData.ContentLength > 0) { string fileSave = Server.MapPath("~/UpLoad/"); int size = fileData.ContentLength; //获取文件的扩展名 string extName = Path.GetExtension(fileData.FileName); //得到一个新的文件名称 string newName = Guid.NewGuid().ToString() + extName; //给模型赋值 Image img = new Image(); img.ImgName = newName; img.ImgSize = size.ToString() ; img.UpLoadTime = System.DateTime.Now; //保存图片的同时,保存images的数据的数据库 MVCEntities db = new MVCEntities(); db.Images.Add(img); db.SaveChanges(); fileData.SaveAs(Path.Combine(fileSave, newName)); } return Content(""); }
保存图片的同时,保持images的数据到数据库。
Home中的视图便是用来显示保存所有已经保存的图片:html视图如下
<body> <div> <table class="table" style="border-collapse: collapse; width: 60%;"> <thead> <tr> <th style="border: 1px solid #0094ff;">ID</th> <th style="border: 1px solid #0094ff;">Photo</th> <th style="border: 1px solid #0094ff;">FileName</th> <th style="border: 1px solid #0094ff;">Size</th> <th style="border: 1px solid #0094ff;">UploadTime</th> </tr> </thead> <tbody id="tbody1"></tbody> </table> <div id="dialog" style="display: none;" title="Dialog Title"> </div> </div></body>
然后具体的数据应该通过js动态来加载:
//html加载时候执行的方法 $(document).ready(function () { $.ajax({ type: ‘GET‘, url: ‘/Home/GetAllUploadImg‘,//通过向这个url请求数据 dataType: ‘json‘, contentType: ‘application/json; charset=utf-8‘, success: function (data, textStatus) { var tbody = $(‘#tbody1‘); $.each(data, function (i, item) { OutputData(tbody, item);//得到返回的数据后,动态加载到html中。 }); } }); });
通过引用jQuery UI的css和js库来实现点击缩略图显示原图:
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" /> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery-ui-1.8.24.js"></script>
而函数function OutputData(tbody, item)的实现如下:
function OutputData(tbody, item) { var uploadTime = new Date(parseInt(item.UpLoadTime.substr(6))); var uploadDate = uploadTime.getFullYear() + "-" + uploadTime.getMonth() + "-" + uploadTime.getDate(); tbody.append("<tr>" + "<td style=\"border: 1px solid #0094ff;\">" + item.Id + "</td>" + "<td style=\"border: 1px solid #0094ff;\">" + "<div id=\"DivImg" + item.Id + "\" />" + "</td>" + "<td style=\"border: 1px solid #0094ff;\">" + item.ImgName + "</td>" + "<td style=\"border: 1px solid #0094ff;\">" + item.ImgSize + "</td>" + "<td style=\"border: 1px solid #0094ff;\">" + uploadDate + "</td>" + "</tr>"); var imgTag = $(‘#DivImg‘ + item.Id); $.get("/Home/GetThumbnailImage", { ImgName: item.ImgName }, function (data) { imgTag.html(data); }); imgTag.click(function () { $("#dialog").dialog({ autoOpen: false, position: ‘center‘, title: item.OldFileName, draggable: false, width: 700, height: 600, resizable: true, modal: true, }).dialog("open"); $.get("/Home/GetImage", { ImgName: item.ImgName }, function (data) { $(‘#dialog‘).html(data); }); }); }
服务端通过GetImage方法获取原图:
public ContentResult GetImage(Image img) { string htmltag = htmltag = "<img id=\"img1\" src=http://www.mamicode.com/"/UpLoad/" + img.ImgName + "\"/>"; return Content(htmltag); }
通过GetThumbnailImage(Image img)获取缩略图:
public ContentResult GetThumbnailImage(Image img) { string ImgUrl = "~/UpLoad/" + img.ImgName; string TempImgUrl="~/Temp/"+img.ImgName; Thumbnail.CreateThumbnail(Server.MapPath(ImgUrl), Server.MapPath(TempImgUrl), 96, 96); string htmltag = htmltag = "<img id=\"img1\" src=http://www.mamicode.com/"/Temp/" + img.ImgName + "\"/>"; return Content(htmltag); }
最后显示的效果如下:
这一节貌似讲的有点乱,因为步骤有点多,而且需要实现和注意的地方不少,下面附上源码,有助于大家研究,有问题可以留言一起讨论:
http://files.cnblogs.com/xmfdsh/MVC%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%98%BE%E7%A4%BA%E7%BC%A9%E7%95%A5%E5%9B%BE%E5%92%8C%E5%8E%9F%E5%9B%BE.zip
MVC图片上传并显示缩略图