如何写一个Js上传图片插件。

项目里面需要一个上传图片的插件,找了半天没有找到满意的,算了 不找了,自己写一个吧,顺便复习一下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

  

猜你喜欢

转载自www.cnblogs.com/jimsfriend/p/10326327.html