項目里面需要一個上傳圖片的插件,找了半天沒有找到滿意的,算了 不找了,自己寫一個吧,順便復習一下js方面的知識。完成之后效果還不錯,當然還要繼續優化,源碼在最后。
介紹一種常見的js插件的寫法
; (function ($, window, document, undefined) { })($, window, document, undefined)
這是一種很常見的寫法,先說這個開頭的 ; 的作用。防止前面上一段scrpit結束的時候沒有分號,執行的時候影響到我們定義的腳本。
然后 一個()包起來的匿名函數,再加上(),等於立刻調用。這么寫的步驟
等同於
function Upload(a,b,c,d) { };
Upload($, window, document, undefined);
即先定義一個函數 Upload, 然后把jquery,window,document,undefined 作為參數執行,
但是后者的寫法等同於誰都能調用 Uplaod 函數,這不是我們想要的 , 使用(function(){})() 好處就是外部無法訪問問這個函數內部,保證內部不會被污染
下面我們開始實踐寫一個jquery上傳圖片插件,一共有三步
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="js/jquery-1.10.2.min.js"></script> </head> <body> <script> ; (function ($, window, document, undefined) { //第一步,定義這個函數,也就是咱們要寫的插件的主體 var Upload = function () { console.log("hello world") };
//第二步,將Upload賦給window,作為window對象的一個屬性
window.Upload = Upload;
})(jQuery, window, document, undefined)
//第三步,開始調用 var upload = new Upload();
</script>
</body>
</html>
當然,我們做的這個上傳圖片插件要有一些功能,
1,可以自定義一些屬性,比如上傳圖片的后端地址,上傳圖片的大小限制,數量限制,等等
2,提供一些可供外部調用的api,比如設置當前的內容,獲取當前的內容,等等
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="js/jquery-1.10.2.min.js"></script> </head> <body> <script> ; (function ($, window, document, undefined) { //第一步,定義這個函數,也就是咱們要寫的插件的主體 var Upload = function (el, setting) { this._default = { maxcount: 5,//默認最大數量5 maxsize: 5,//默認圖片最大5M }; this._options = $.extend(this._default, setting);//通過$.extend 函數可以讓兩個對象合並,得到一個新的對象,options來存放配置的屬性 this.getValue = function () { console.log(this._options); }; this.setValue = function (arr) { }; } //第二步,將Upload賦給window,作為window對象的一個屬性 window.Upload = Upload; })(jQuery, window, document, undefined) //第三步,開始調用 var upload = new Upload({"url":"/tools/upload","maxcount":10}); //創建實例 upload.getValue(); //在外部調用api
</script> </body> </html>
經過反復的修改,終於完成了,附上調用和效果圖
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <link href="css/mini-upload.css" rel="stylesheet" /> <script src="js/jquery-1.10.2.min.js"></script> <script src="js/mini-upload.js"></script> </head> <body> <!--第一步,創建一個div容器--> <div id="test"></div> <input type="button" onclick="getvalue()" value="獲取當前值" /> <input type="button" onclick="setvalue()" value="設置當前值" /> <script> //第二步,實例化一個插件對象 var upload = new Upload("#test", { // data:[], //設置默認的值 url: "/tools/upload" }); //獲取當前插件的值,返回一個數組,是所有圖片地址的數組 function getvalue() { console.log(upload.getValue()); } //設置當前的值,返回一個數組,是所有圖片地址的數組 function setvalue() { var arr = ["https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3890934586,2525313398&fm=58&s=37AAF104D22336A5C63010930300C080" , "https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=2420047149,2850547244&fm=58&s=49099B555E23771B16B104F80300C02F"]; upload.setValue(arr); } </script> </body> </html>
也就200行代碼
后端代碼
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Caching; using System.Web.Mvc; namespace MiniUpload.Controllers { public enum ResultState { SUCCESS = 0, WARNING = 2, FAIL = 4, NOTIFY = 8, } public class ToolsController : Controller { public JsonResult JSON(ResultState state, object data = null, string msg = null) { JsonResult j = new JsonResult(); string m = state.ToString(); if (!string.IsNullOrEmpty(msg)) { m = msg; } j.Data = new { msg = m, code = (int)state, data = data }; j.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return j; } public ActionResult Upload( ) { try { int max = 5;//5M上限 string[] allow = new string[] { ".jpg", ".jpeg", ".png", ".jif", ".bmp" }; if (System.Web.HttpContext.Current.Request.Files.Count > 0) { var file = System.Web.HttpContext.Current.Request.Files[0]; string fix = file.FileName.Substring(file.FileName.LastIndexOf('.')); if (!allow.Contains(fix.ToLower()))//是圖片 { return JSON(ResultState.FAIL, null, "不允許的文件類型"); } if (file.ContentLength > max*1024*1024)//最大限制 { return JSON(ResultState.FAIL, null, "超出了最大限制 "); } string path = "/UploadFile"; string dic = Server.MapPath(path); if (!System.IO.File.Exists(dic)) { System.IO.Directory.CreateDirectory(dic); } string filename = path+"/" + Guid.NewGuid().ToString() + fix; file.SaveAs(Server.MapPath(filename)); string url = "http://" + System.Web.HttpContext.Current.Request.Url.Authority + filename; return JSON(ResultState.SUCCESS, url); } return JSON(ResultState.FAIL, null, "NoFile"); } catch (Exception e) { return JSON(ResultState.FAIL, e.ToString()); } } } }
實踐用起來還行,當然后面還要繼續改進
附上 源碼地址 https://gitee.com/unclescar/mini-upload