用form表单input type="file"上传文件(提交前判断)

1、用/jquery.form.js上传文件,提交前判断是否选择了文件(之前很纠结判断问题,写在beforeSend里面不管什么情况都会提交)

2、用ajax接收信息

3、优化提交按钮样式

用form表单input type=


HTML页面代码:


   

       

Upload File   


       
action="/Ajax.ashx?action=SendFiles"role="form" method="post" ENCTYPE="multipart/form-data" οnsubmit="return checkUser();">
           

                

                    Select file :up
                   

                

                
                
                
                
           

       

   



Ajax.ashx代码:

public void ProcessRequest(HttpContext context)
        {
            //操作
            string action = context.Request.QueryString["action"];

            //检查来源
            if (!ComUtls.CheckPostSource())
            {
                context.Response.Write(ORes.Error.SuspiciousOfPostingSourceAndBeIgnored);
                return;
            }

            /****************************************
             * 加快方法调用响应速度,所有方法和属性尽量以静态的形式实现
             ***************************************/

            switch (action)
            { 

                    case "IndexSendLeaveword01": IndexSendLeaveword01(); break;

             }
        }

       ///


        /// 提交图片
        ///

        private static void IndexSendLeaveword01()
        {
            // 获取参数
            string upfile = GF("uploadedfile");

            string filetitle = "";
            //安全检查
            **省略**

            string filiepath = "";
            HttpPostedFile imgFile = HttpContext.Current.Request.Files["uploadedfile"];
            if (imgFile != null)
            {
                String fileName = imgFile.FileName;
                String fileExt = System.IO.Path.GetExtension(fileName).ToLower();
                if (imgFile.InputStream == null || imgFile.InputStream.Length > 5 * 1024 * 1024)
                {
                    WriteState(0, "Upload file size limit.");
                    return;
                }
                string gs = "gif,jpg,png,docx,doc,xls,txt,pdf,rar,zip,ppt,xlsx";
                if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(gs.Split(','), fileExt.Substring(1).ToLower()) == -1)
                {
                    WriteState(0, "Upload file extension is not allowed.\n Only allow" + gs + "format。");
                    return;
                }
                string path = "/uploadfiles/temporary/";
                String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo) + fileExt;
                try
                {
                    filiepath = path + newFileName;
                    filetitle = newFileName;
                    string save = NSW.Utls.IOUtls.GetMapPath(path);
                    if (!System.IO.Directory.Exists(save))
                    {
                        System.IO.Directory.CreateDirectory(save);
                    }
                    imgFile.SaveAs(System.IO.Path.Combine(save, newFileName));
                }
                catch (Exception ex)
                {
                    WriteState(0, ex.ToString());
                    Log.Error(ex);
                    return;
                }
            }
            else
            {
                WriteState(0, "Please select the file you want to upload.");
                return;
            }

           //填充实体
            tbTBAA nobj = new tbTBAA();
            nobj.filemane= filiepath;//上传文件地址

           //保存到数据库
            int rowsAffected = DbSession.Default.Save(nobj);
            //显示提示
            if (rowsAffected > 0)
            {
                string msg = "Thank you for uploading the design draft, we will contact you as soon as possible.";
                WriteState(1, msg);
            }
            else
            {
                WriteState(0, "Sorry, submit failed, please try again later.");
            }

}


       ///


        /// 获取表单值Request.Form,获取失败则返回 string.Empty
        ///

        /// 参数名
        /// 参数值
        private static string GF(string paraName)
        {
            string val = HttpContext.Current.Request.Form[paraName];
            if (val == null) { return ""; }
            if (Regex.IsMatch(val, StrRegex))
            {
                HttpContext.Current.Response.Write("The parameters you submitted are not valid!");
                HttpContext.Current.Response.End();
                return "";
            }
            else
            {
                return val == null ? string.Empty : val.Trim();
            }
        }

        ///


        /// 输出状态值与消息
        ///

        /// 状态值
        /// 消息
        protected static void WriteState(int state, string msg)
        {
            KeyValuePair node = new KeyValuePair("state", state.ToString());
            KeyValuePair node2 = new KeyValuePair("msg", msg);
            WriteXml(node, node2);

        }


css样式


.up_com .upbtn{ position:relative;margin:15px 0 ; text-align:center;}
.up_com .pc{ width:211px; height:70px; line-height:70px; display:block;padding:29px 49px; text-align:center;margin:30px auto 30px; border: 1px solid #ebebeb;  box-shadow: 0 0 5px #ccc; }
.up_com .pc img{ width:70px; float:right; display:block; }
.up_com .pc a{ display:block;}
.up_com .pc .btn{font-size:16px;color:#333; line-height:70px; display:block; height:70px; float:left;}
.up_com #uploadedfile{filter:alpha(opacity=0);  -moz-opacity:0; -khtml-opacity:0;opacity: 0;width:325px; height:150px; position:absolute; top:0; left:50%;z-index:2; cursor:pointer;margin-left: -162px; }
.up_com #txtfilename{ font-size:14px; color:#333;}
.up_com .zsk7{width:200px; height:39px; line-height:39px; font-size:14px; font-weight:bold; color:#FFF; background:#6a6a6a url("Img/Index/up.png") no-repeat 30px center; border:0px;box-shadow: 2px 2px 2px 0 #a1a1a1; }




你可能感兴趣的:(html,JQuery,Js)