zoukankan      html  css  js  c++  java
  • JQuery异部上传多个文件

    这个例子需要用到JQuery和一个JQuery插件ajaxupload.js,不说太多。直接上代码:

    前台:

     <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
        <script src="Scripts/ajaxupload.js" type="text/javascript"></script>

     <script type="text/javascript">
            $(document).ready(function () {
                new AjaxUpload('#buttonUpload', {
                    action: 'Handler2.ashx',
                    data: { Folder: 'commodity', Count: $("#hidd_imgCount").val() },
                    onSubmit: function (file, ext) {
                        $("#loading").show();
                        if (!/^(jpg|bmp|png|gif)$/.test(ext)) {
                            alert("只能上传格式为(bmp、jpg、png、gif)格式的图片!");
                            return false;
                        }
                        //判断上传图片的数量
                        var imgCount = $("#hidd_imgCount").val();
                        if (parseInt(imgCount) >= 5) {
                            alert("最多只能上传5张图片!");
                            $("#loading").hide();
                            return false;
                        }
                        this.disable();
                    },
                    onComplete: function (file, response) {
    
                        $("#loading").hide();
                        this.enable();
                        var responseText = response.toString();
                        if (/MSIE 6.0/i.test(navigator.userAgent)) {
                            responseText = getCookies();
                        }
                        //显示1
                        var reArray = responseText.split('|');
                        if (reArray[0] == "1") {
                            alert("上传的文件不能大于4MB!");
                            return false;
                        }
                        else if (reArray[0] == null || reArray[0] == "") {
                            alert("上传失败!");
                            return false;
                        }
                        else {
                            var param = reArray[1];
                            if (reArray.length >= 3) {
                                param += "|" + reArray[2];
                            }
                            var divDocument = "<div id=\"" + reArray[1].substring(0, reArray[1].lastIndexOf('.') - 1) + "\" class=\"div_upfiles\">" + file + "     <a href=\"javascript:;\" onclick=\"delAttach('" + param.toString() + "','" + file + "');\">删除</a>" + "</div>";
                            $("#div_Result").append(divDocument);
                        }
                        //用于记录,上传的图片
    
                        document.getElementById("hidd_UploadFiles").value += param + "%" + file + "&";
                        var imgCount = $("#hidd_imgCount").val();
                        $("#hidd_imgCount").val(parseInt(imgCount) + 1);
                    }
                });
            });
            function delAttach(param, showName) {
                $.ajax({
                    url: "RemoveImage.ashx?ID=" + param,
                    success: function (result) {
                        if (result.toString() != "false") {
                            $("#div_Result").remove("#" + result);
                            $("#" + result).replaceWith("");
                            //移除内容,同时更新Hidd
                            var oldVal = $("#hidd_UploadFiles").val();
                            var newVal = oldVal.replace(param + "%" + showName + "&", "");
    
                            $("#hidd_UploadFiles").val(newVal);
                            var imgCount = $("#hidd_imgCount").val();
                            $("#hidd_imgCount").val(imgCount - 1);
                        }
                    }
                });
            }
    
            //当点击Submit引发回调,且并没有提交成功,引发回调时,重新载入上传UploadFiles部分
            function reloadUpFiles() {
                var hidd = $("#hidd_UploadFiles").val();
                if (hidd != "") {
                    var arrayFiles = hidd.split('&');
                    $("#div_Result").html("");
                    for (var i = 0; i < arrayFiles.length; i++) {
                        if (arrayFiles[i].toString().length > 0) {
                            var aFile = arrayFiles[i].split('%');
                            var sysName = aFile[0].toString();
                            var showName = aFile[1].toString();
                            var divDocument = "<div id=\"" + sysName.substring(0, sysName.lastIndexOf('.') - 1) + "\" class=\"div_upfiles\">" + showName + "   <a href=\"javascript:;\" onclick=\"delAttach('" + sysName + "','" + showName + "');\">删除</a>" + "</div>";
                            $("#div_Result").append(divDocument);
                        }
                    }
                }
            }
            function getCookies() {
                var cookies = document.cookie;
                var innerText = cookies.substring(cookies.lastIndexOf('ImgResponse=') + 12, cookies.lastIndexOf('{1}'));
                return innerText;
            }
    </script>
    CSS:

     <style type="text/css">
            .div_upfiles
            {
                background-image: url('images/img.jpg');
                background-repeat: no-repeat;
                height: 14px;
                padding-left: 20px;
                font: normal 12px Verdana;
                padding-top: 1px;
                margin-bottom: 5px;
                color: #0A3761;
            }
            .btn_delete
            {
                border: solid 0px white;
                background-color: White;
            }
        </style>

    HTML代码:

     <div id="loading" style="display: none;">
                <img src="images/loading.gif"></div>
            <div id="div_Result">
            </div>
            <input type="button" id="buttonUpload" value="上传" />
     	<asp:HiddenField ID="hidd_UploadFiles" runat="server" />
            <asp:HiddenField ID="HiddenField1" runat="server" Value="0" />
            <input id="hidd_imgCount" type="hidden" value="0" />
    然后是两个异部提交的文件:


    上传文件后台代码:

    public class Handler2 : IHttpHandler
    {
    
        public void ProcessRequest(HttpContext context)
        {
            System.Threading.Thread.Sleep(2000);
            string oldName = context.Request.Files["userfile"].FileName;
    
            string type = oldName.Substring(oldName.LastIndexOf('.'));
            string Count = context.Request["Count"].ToString();
            string strFileName = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Guid.NewGuid() + DateTime.Now.Ticks.ToString(), "MD5") + Count + type;
            string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
            string folder = context.Request["Folder"].ToString();
            int bytes = context.Request.Files[0].ContentLength;
            //如果,上传的文件大于4MB的话,抛消息出来
            if (bytes > 4 * 1024 * 1024)
            {
                ResponseWriteEnd(context, "1");
            }
    
            string strLocation = string.Empty;
    
            if (string.IsNullOrEmpty(folder))
            {
                strLocation = (context.Server.MapPath("uploadFiles") + ("//" + strFileName));
            }
            else
            {
                //判断 目录 是否存在。。不存在则创建
                string path = context.Server.MapPath("uploadFiles/" + folder + "/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                strLocation = path + ("//" + strFileName);
            }
            context.Request.Files[0].SaveAs(strLocation);
    
            context.Response.ContentType = "text/plain";
    
            string ResponseString = "0|" + strFileName + (!string.IsNullOrEmpty(folder) ? "|" + folder : "");
    
            ResponseWriteEnd(context, ResponseString);
    
        }
        /// <summary>
        /// 用于输出流,并终止流
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <param name="msg">你输出流信息</param>
        private void ResponseWriteEnd(HttpContext context, string msg)
        {
            context.Response.Write(msg);
            context.Response.Cookies["ImgResponse"].Value = msg + "{1}";
            context.Response.End();
        }

    删除文件后台代码:

    public class RemoveImage : IHttpHandler
    {
    
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string parameters = context.Request.QueryString["ID"].ToString();
            var ParamArray = parameters.Split('|');
            string filename = ParamArray[0];
            string Path = "";
            string Folder = string.Empty;
            if (ParamArray.Length > 1)
            {
                Folder = ParamArray[1]+ "/";
            }
            Path = context.Server.MapPath("uploadFiles/" + Folder + "" + filename);
            if (File.Exists(Path))
            {
                File.Delete(Path);
                ResponseWriteEnd(context, filename.Substring(0, filename.LastIndexOf('.') - 1));
            }
            else
            {
                ResponseWriteEnd(context, "false");
            }
        }
    
        /// <summary>
        /// 用于输出流,并终止流
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <param name="msg">你输出流信息</param>
        private void ResponseWriteEnd(HttpContext context, string msg)
        {
            context.Response.Write(msg);
            context.Response.End();
        }
    

    运行结果如下图:



    如果需要源码的朋友可以到:http://download.csdn.net/detail/work201003/3973051进行下载

  • 相关阅读:
    行业观察(五)| 服装零售企业数字化升级要“落地有数”
    奇点云 x 阿里云 | 联合发布综合体数字化转型与数据创新解决方案
    StartDT_AI_Lab | 开启“数据+算法”定义的新世界
    奇点云数据中台技术汇(六)| 智能算法助力企业效率升级
    从《长安十二时辰》看企业中台战略
    django1.9版本数据库建立
    django中html文件的配置
    python的django建立项目
    python 读取excel表格的数据
    python创建excel表格比并存入数据
  • 原文地址:https://www.cnblogs.com/raphael5200/p/5114872.html
Copyright © 2011-2022 走看看