zoukankan      html  css  js  c++  java
  • Mvc利用淘宝Kissy uploader实现图片批量上传附带瀑布流的照片墙

    前言

      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; 118px;border-top: 1px solid #E2E2E2;height: 25px;}
            .sub{height:30px; 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上传,当遇到移动设备时发现不支持上传了,采用该插件则不会出现此问题。

  • 相关阅读:
    angularjs的$on、$emit、$broadcast
    angularjs中的路由介绍详解 ui-route(转)
    ionic入门教程-ionic路由详解(state、route、resolve)(转)
    Cocos Creator 加载使用protobuf第三方库,因为加载顺序报错
    Cocos Creator 计时器错误 cc.Scheduler: Illegal target which doesn't have uuid or instanceId.
    Cocos Creator 构造函数传参警告 Can not instantiate CCClass 'Test' with arguments.
    Cocos Creator 对象池NodePool
    Cocos Creator 坐标系 (convertToWorldSpaceAR、convertToNodeSpaceAR)
    Cocos Creator 常驻节点addPersistRootNode
    Cocos Creator 配合Tiled地图的使用
  • 原文地址:https://www.cnblogs.com/sky-net/p/4367275.html
Copyright © 2011-2022 走看看