uploadify上传控件使用

这两天将uploadify插件和SWFupload插件进行了整理。我是根据同事在项目中用了,然后整理了下,下次遇到自己也可以用用。

基于jquery的文件上传控件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,删除已上传文件。

http://www.uploadify.com/documentation/       这是插件的一些事件属性,必要时可以查看。插件可以去官网下。我用的3.1版本。版本不同差别很大。

需要的文件:主要的其实也就一个JS文件,一个CSS样式文件。官网是.net版本的我这里是.net的。

<link href="~/Content/Uploadify/v3.1/uploadify1.css" rel="stylesheet" />
<script src="~/Content/Uploadify/jquery-1.4.2.min.js"></script>
<script src="~/Content/Uploadify/v3.1/jquery.uploadify-3.1.js"></script>
主要就是这三个吧。还有一些图片路径什么的这里不细说

样式

<style type="text/css">
    #divImg {
            width: 100%;
            text-align: left;
            margin-left: 1%;
        }

            #divImg img {
                border-radius: 5px;
            }

        .divItem {
            float: left;
            width: 198px;
            height: 112px;
            margin: 7px;
        }

        .ScenicImg {
            width: 200px;
            height: 112px;
            margin: 5px;
        }
     .delImg {
            width: 20px;
            height: 20px;
            float: left;
            position: relative;
            top: -116px;
            left: 5px;
            cursor: pointer;
        }
      .control-group {
            float: left;
            width: 50%;
        }
</style>

JS代码

<script type="text/javascript">
        $(function () {
            var uploadLimit = 10;
            //InitEidt();//修改的初始化方法
            var isFinish = true;//用来验证是否上传完成
            $('#uploadify').uploadify({
                'buttonText': '上传',
                'queueID': "fileQueue",
                'buttonClass': 'browser',
                'auto': true,//是否为自动上传,true是,false不是
                'removeCompleted': false,
                'swf': '/Content/Uploadify/v3.1/uploadify.swf',
                'uploader': '/Content/Uploadify/UploaddifyHandler.ashx',
                'fileTypeExts': '*.png; *.jpg; *.jpeg; *.bmp; *.gif',
                'fileDataName': 'Filedata',
                'queueSizeLimit': uploadLimit,
                'folder': 'upload',
                'height': 18,
                'width': 75,
                'errorMsg': "1111",
                'onUploadSuccess': function (file, returndata) {
                    var fileObject = $.parseJSON(returndata);
                    isFinish = false;//刚开始上传,默认为false
                    var cancel = $("#" + file.id + " .cancel a");
                    if (cancel) {
                        cancel.live('click', function () {
                            //通过uploadify的settings方式重置上传限制数量
                            $('#upload').uploadify('settings', 'uploadLimit', ++uploadLimit);
                            //防止手快多点几次x,把x隐藏掉
                            $(this).hide();
                            //隐藏对应的图片
                            $("#result").hide();
                        })
                    }

                    $('#uploadify').uploadify('settings', 'queueSizeLimit', uploadLimit);
                    var mes = fileObject.NewFileName;//保存在文件路径下的名称

                  

                    var serverPath = "/Upload/SBLY/" + mes;//文件保存路径  ~/Upload/SBLY/201705231316368306.png

                    $("#divImg").show();
                    $("#divImg").append("<div class='divItem'><img class='ScenicImg' src='" + serverPath + "' /><img  class='delImg' src='/Content/Images/icon_cont_close.png' alt='删除'/><input type='hidden' name='hidimgpath' value='" + serverPath + "' /></div>");
                    $("#" + file.id).remove();
                    if (res == "0") {
                        alert(mes);
                        return;
                    } else {

                    }
                },
                'onUploadComplete': function (e) {
                    isFinish = true;//上传完成后设置为true

                }
            });
           // InitFileImg();//该方法是上传之后刷新页面显示之前上传过的图片,也及时初始化图片。demo没必要加这段,实际开发中需要,所以我先注释了

            $(".delImg").live("click", function () {
                $(this).closest("div").remove();
            })
          

        });
//该方法是上传之后刷新页面显示之前上传过的图片。重新加载页面,后台数据库取出图片的路径加载在页面上。demo没必要加这段,实际开发中需要,所以我先注释了
 function InitFileImg() {

            var jsonResult = '@Html.Raw(ViewData["FileList"].ToString())';//后台传过来的JSON格式的图片路径集合
           
            if (jsonResult.length == 0) { return false; }

            var filelist = eval(jsonResult);
           
            var ResultStr = "";
            //获取文件目录
            var curWwwPath = window.document.location.href;
            var pathName = window.document.location.pathname;
            var pos = curWwwPath.indexOf(pathName);
            var localhostPaht = curWwwPath.substring(0, pos);
            //获取文件目录
            for (var i = 0; i < filelist.length; i++) {
                ResultStr += "<div class='divItem'><img class='ScenicImg' src='" + localhostPaht + filelist[i].filePath + "' /><img class='delImg' src='/Content/Images/icon_cont_close.png' alt='删除'/><input type='hidden' name='hidimgpath' value='" + filelist[i].filePath + "' /></div>";
            }
            $("#divImg").append(ResultStr);
        }
     </script>

HTML代码

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <div class="control-group" style="width:100%;clear:left;">
            
                <div class="controls" id="fileQueue">
                    <input type="file" id="uploadify" name="FileData" accept=".jpg,.jpeg,.png,.gif,.bmp" class="form-control" />
                </div>
            </div>
            <div class="control-group" id="divImg">

            </div>
    </div>
</body>
</html>


后台代码

var f = new FileInfo();
            try
            {
   context.Response.ContentType = "text/plain";
                context.Response.Charset = "utf-8";
                HttpPostedFile file = context.Request.Files["FileData"];
                string uploadPath = HttpContext.Current.Server.MapPath((@"~/Upload/SBLY/"));
                string fileSaveName = DateTime.Now.ToString("yyyyMMddHHmmssffff");

                if (file != null)
                {
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }

                    var savepathtmp = uploadPath + file.FileName;
                    var exe = Path.GetExtension(savepathtmp);
                    var newsavepath = uploadPath + fileSaveName + exe;

                    System.IO.FileInfo finfo = new System.IO.FileInfo(newsavepath);
                    string fileType = finfo.Extension;
                    if (IsAllowFile(fileType))
                    {
                        file.SaveAs(newsavepath);
                    }

                    f.SourceFileName = file.FileName;
                    f.SaveFilePath = newsavepath;
                    f.NewFileName = fileSaveName + exe;
                }

            }
            catch (Exception ex)
            {

                f.SourceFileName = "";
                f.SaveFilePath = "";
            }
            finally
            {
                context.Response.ContentType = "text/plain";

                context.Response.Write(SerializationHelper.JsonSerialize(f));
            }
 /// <summary>
        /// 判断上传文件是否在允许范围内
        /// </summary>
        /// <param name="fileExd">文件后缀</param>
        /// <returns></returns>
        public bool IsAllowFile(string fileExd)
        {
            fileExd = fileExd.ToLower();
            string[] allowExds = new string[] { ".jpg", ".bmp", ".gif", ".jpeg", ".png" };

            if (allowExds.Contains(fileExd))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 文件信息
        /// </summary>
        public class FileInfo
        {
            /// <summary>
            /// 原始文件名称
            /// </summary>
            public string SourceFileName { set; get; }

            /// <summary>
            /// 保存在服务器上的物理路径 ,文件名称已经改过成临时文件名
            /// </summary>
            public string SaveFilePath { get; set; }
            /// <summary>
            /// 文件新名称
            /// </summary>
            public string NewFileName { get; set; }

        }

最后是效果图:上传过程中带进度条的



猜你喜欢

转载自blog.csdn.net/qq_34571519/article/details/74560681
今日推荐