前言
KISSY 是由阿里集團前端工程師們發起創建的一個開源 JS 框架。它具備模塊化、高擴展性、組件齊全,接口一致、自主開發、適合多種應用場景等特性。本人在一次項目中層使用這個uploader組件。
關於kissy uploader:
Uploader是非常強大的異步文件上傳組件,支持ajax、iframe、flash三套方案,實現瀏覽器的全兼容,調用非常簡單,內置多套主題支持和常用插件,比如驗證、圖片預覽、進度條等。
廣泛應用於淘寶網,比如退款系統、愛逛街、二手、拍賣、我的淘寶、賣家中心、導購中心等。
擁有非常不錯的擴展性,可以自己定制主題和插件。
uploader的特性:
- 支持ajax、flash、iframe三種方案,兼容所有瀏覽器。(iframe不推薦使用)
- 多主題支持,可以自己定制主題
- 支持多選批量上傳
- 支持上傳進度顯示
- 支持取消上傳
- 支持圖片預覽(使用flash上傳不支持)
- 支持上傳驗證
- 多種配置方式
Kissy uploader配置簡單而且使用方便,官網提供許多主題稍加修改便可用於項目當中,本文的案例采用的是kissy uploader的在線js庫。更多的資料大家可以去官網:http://gallery.kissyui.com/uploader/1.4/guide/index.html#demo匯總查找相關資料,講述的很全面。
案例截圖
相關配置
1、本文照片的相關信息我采用EF coder first將其保存在數據庫中了,相關代碼
實體類:

[Table("Photos")] public class Photos { [Key] public int ID { get; set; } public string Name { get; set; } public string Desc { get; set; } public string Src { get; set; } public DateTime? PubliseTime { get; set; } }
數據庫上下文:

public class PhotoDB:DbContext { public PhotoDB() : base("name=PhotoDB") { } public DbSet<Photos> Photos { get; set; } }
連接字符串:

<connectionStrings> <add name="PhotoDB" connectionString="server=(local);Initial Catalog=Photo;Integrated Security=SSPI" providerName="System.Data.SqlClient" /> </connectionStrings>
2、上傳圖片配置(相關配置說明大家可以參考官網示例)
上傳頁面index:

<!doctype html> <html> <head> <meta charset="utf-8"/> <script src="http://a.tbcdn.cn/s/kissy/1.3.0/kissy-min.js" charset="utf-8"></script> <style type="text/css"> .textvalue{padding: 0;width: 118px;border-top: 1px solid #E2E2E2;height: 25px;} .sub{height:30px; width:120px;position:relative;top:30px;} </style> </head> <body> @using (Html.BeginForm()) { <div class="grid"> <input type="file" class="g-u" id="J_UploaderBtn" value="上傳圖片" name="Filedata" /> <input type="hidden" id="J_Urls" name="urls" value="" /> <div class="g-u">還可以上傳<span id="J_UploadCount">14</span>張圖片</div> </div> <ul id="J_UploaderQueue" class="grid"> <script type="text/uploader-theme"> <li id="queue-file-{id}" class="g-u" data-name="{name}" style="height: 140px !important"> <div class="pic"> <a href="javascript:void(0);"><img class="J_Pic_{id} preview-img" src="" /></a> </div> <div class=" J_Mask_{id} pic-mask"></div> <div class="status-wrapper"> <div class="status waiting-status"><p>等待上傳,請稍候</p></div> <div class="status start-status progress-status success-status"> <div class="J_ProgressBar_{id}"><s class="loading-icon"></s>上傳中...</div> </div> <div class="status error-status"> <p class="J_ErrorMsg_{id}">上傳失敗,請重試!</p> </div> </div> <a class="J_Del_{id} del-pic" href="#">刪除</a> <input type="text" value="" name="desc" id="desc" class="textvalue" placeholder="描述"> </li> </script> </ul> <input type="submit" value="保存" class="sub" /> } <script type="text/javascript"> var S = KISSY; if (S.Config.debug) { var srcPath = "../../../../"; S.config({ packages: [ { name: "gallery", path: srcPath, charset: "utf-8" } ] }); } var $ = S.Node.all; S.use('gallery/uploader/1.4/index,gallery/uploader/1.4/themes/imageUploader/index,gallery/uploader/1.4/themes/imageUploader/style.css', function (S, Uploader, ImageUploader) { //上傳插件 var plugins = 'gallery/uploader/1.4/plugins/auth/auth,' + 'gallery/uploader/1.4/plugins/urlsInput/urlsInput,' + 'gallery/uploader/1.4/plugins/proBars/proBars,' + 'gallery/uploader/1.4/plugins/filedrop/filedrop,' + 'gallery/uploader/1.4/plugins/preview/preview'; S.use(plugins, function (S, Auth, UrlsInput, ProBars, Filedrop, Preview) { var uploader = new Uploader('#J_UploaderBtn', { //處理上傳的服務器端腳本路徑 action: "/Home/PictureUpload", multiple: true }); //上傳成功后顯示圖片描述 uploader.on('success', function (ev) { var result = ev.file.result; if (result.desc) { var $desc = $('.J_Desc_' + ev.file.id); $desc.html(result.desc); } }) //使用主題 uploader.theme(new ImageUploader({ queueTarget: '#J_UploaderQueue' })) //驗證插件 .plug(new Auth({ //最多上傳個數 max: 14, //圖片最大允許大小 maxSize: 2000 })) //url保存插件 .plug(new UrlsInput({ target: '#J_Urls' })) //進度條集合 .plug(new ProBars()) //拖拽上傳 .plug(new Filedrop()) //圖片預覽 .plug(new Preview()) ; //渲染默認數據 uploader.restore(); }); }) </script> </body> </html>
后台臨時保存方法:
//圖片上傳處理 public ActionResult PictureUpload() { //保存到臨時文件 HttpPostedFileBase postedfile = Request.Files["Filedata"]; var filename = postedfile.FileName; var newname =Guid.NewGuid()+filename.Substring(filename.LastIndexOf('.')); var filepath = Server.MapPath("/UpLoad/temp/") + newname; Image image = Image.FromStream(postedfile.InputStream, true); image.Save(filepath);//保存為圖片 return Json(new { status = 1, url = "/UpLoad/temp/" + newname }); }
表單提交保存數據相關方法:
[HttpPost] public ActionResult Index(string urls, FormCollection fc) { var urlArray = urls.Split(','); var desArray = fc["desc"].Split(','); for (int i = 0; i <desArray.Length; i++) { //保存為正式文件 var filename = urlArray[i].Substring(urlArray[i].LastIndexOf('/') + 1); var oldfile = Server.MapPath(urlArray[i]); var newfile = Server.MapPath("/UpLoad/photo/")+filename; System.IO.File.Move(oldfile, newfile); db.Photos.Add( new Photos { Name = filename, Desc = desArray[i], Src = "/UpLoad/photo/"+filename, PubliseTime = DateTime.Now } ); } db.SaveChanges(); return View(); }
3、瀑布流照片牆
后台返回所有照片實體類傳遞給視圖;
//照片牆 public ActionResult Photo() { var photos = db.Photos.ToList(); return View(photos); }
前台動態加載圖片js及照片牆頁面:
@model List<MvcApplication3.Models.Photos> @{Layout = null;} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>jQuery實現的瀑布流布局的圖片特效代碼</title> <link href="../../Content/lanrenzhijia.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script src="../../Scripts/blocksit.min.js" type="text/javascript"></script> <script> $(document).ready(function () { //vendor script $('#header') .css({ 'top': -50 }) .delay(1000) .animate({ 'top': 0 }, 800); $('#footer') .css({ 'bottom': -15 }) .delay(1000) .animate({ 'bottom': 0 }, 800); //blocksit define $(window).load(function () { $('#container').BlocksIt({ numOfCol: 5, offsetX: 8, offsetY: 8 }); }); //window resize var currentWidth = 1100; $(window).resize(function () { var winWidth = $(window).width(); var conWidth; if (winWidth < 660) { conWidth = 440; col = 2 } else if (winWidth < 880) { conWidth = 660; col = 3 } else if (winWidth < 1100) { conWidth = 880; col = 4; } else { conWidth = 1100; col = 5; } if (conWidth != currentWidth) { currentWidth = conWidth; $('#container').width(conWidth); $('#container').BlocksIt({ numOfCol: col, offsetX: 8, offsetY: 8 }); } }); }); </script> </head> <body> <!-- Content --> <section id="wrapper"> <div id="container"> @foreach (var item in Model) { <div class="grid"> <div class="imgholder"> <img src="@item.Src" /> </div> <strong>@item.Desc</strong> <p>上 傳 時 間:</p> <div class="meta">@item.PubliseTime.ToString()</div> </div> } <!----> </div> </section> </body> </html>
瀑布流采用國外的一個jquery插件實現。
結語
本人強烈推薦采用kissy uploader上傳插件,原因在於:采用的上傳方案,當值是數組時,比如“type” : ["flash","ajax","iframe"],按順序獲取瀏覽器支持的方式,該配置會優先使用flash上傳方式,如果瀏覽器不支持flash,會降級為ajax,如果還不支持ajax,會降級為iframe;當值是字符串時,比如“type” : “ajax”,表示只使用ajax上傳方式。這種方式比較極端,在不支持ajax上傳方式的瀏覽器會不可用;當“type” : “auto”,auto是一種特例,等價於["ajax","iframe"]。這一點很重要,由於以前一個項目采用flash上傳,當遇到移動設備時發現不支持上傳了,采用該插件則不會出現此問題。
文章結束,建議大家一塊推薦此插件,順便頂下文章,呵呵。