之前公司有需求要实现后台系统的图片添加修改,图片都保存在服务器上,框架采用Easy UI+AJAX+ashx的传统方式:

1 <input id="txtNewsImage" name="imgFile1" class="easyui-filebox" style="width: 200px; font-size: 15px" data-options="prompt:'选择一张图片...',buttonText:'点击选择',editable:false" />

HTML标签中,使用class="easyui-filebox"进行文件框初始化,使用data-options中的prompt属性标记文本框提示语,buttonText属性设置上传按钮的文本,editable属性限制文本框的用户输入

在上面的input标签外层要套一个form表单

1  <form id="form1" method="post" enctype="multipart/form-data" class="easyui-form" data-options="novalidate:true"></form>

完整的写法应该是:

1 <form id="form1" method="post" enctype="multipart/form-data" class="easyui-form" data-options="novalidate:true">
2   <input id="txtNewsImage" name="imgFile1" class="easyui-filebox" style="width: 200px; font-size: 15px" data-options="prompt:'选择一张图片...',buttonText:'点击选择',editable:false" />
3 </form>
method="post" enctype="multipart/form-data"是设置form表单的上传属性的,必须得加。data-options="novalidate:true"如果你的表单里没有用到easyui的验证机制,可以使用这句话,才能实现上传

然后就是要利用Jquery和EasyUI的语法来上传了

1         $("#txtNewsImage").filebox({
 2             onChange: function (newValue, oldValue) {
 3                 if ($("#txtNewsImage").filebox("getText") == "") {
 4                     $.messager.alert('提示', "请先上传图片", 'warning');
 5                     return;
 6                 }
 7                 $('#form1').form('submit', {
 8                     url: "Hdr_Upload.ashx?method=UpImage&filename=imgFile1&oldName=" + oldName,
 9                     success: function (result) {
10                         result = $.parseJSON(result);
11                         if (result.error != "0") {
12                             $.messager.alert('提示', result.error, 'warning');
13                             return;
14                         }
15                         $("#img1").attr("src", result.url);//img1是图片的预览
16                     }
17                 });
18             }
19         });

前面是filebox的改变事件,就是当用户点击按钮并且上传了一个文件后触发的事件。后面的form是使用了easyui的表单submit提交方法,url是后端提供的一般处理程序接口,method是方法选择器(可以无视),filename是filebox的name属性,因为上传文件时,一般处理程序里的context.Request.Files[filename],需要按照名称找到图片,所以最好传一个name,并且要和那个filebox的name一样。oldname是我后来加的,为了在修改的时候删除原来的旧图片(可以无视)。

/// <summary>
        /// 上传展示图片  格式: /Upload/image/151126/201511261120413957.png  返回值: error为0则上传成功,url为图片成功的路径
        /// </summary>
        /// <param name="context"></param>
        public void UpImage(HttpContext context)
        {
            string tempFileName = "";
            string newPath = "";
            string UrlPath = "";
            string error = "0";
//生成文件名
            string year = DateTime.Now.Year.ToString().Substring(2, 2);
            string month = DateTime.Now.Month.ToString().Length == 1 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString();
            string day = DateTime.Now.Day.ToString().Length == 1 ? "0" + DateTime.Now.Day.ToString() : DateTime.Now.Day.ToString();
            string erji = year + month + day;

            string PicPath = ConfigurationManager.AppSettings["imgWuli"].ToString() + "Upload/image/" + erji;  //设置存储路径,我这里使用了配置文件里的前部分路径

            string filename = context.Request["filename"];

            //从表单文件列表中根据name找到上传的那个文件
            HttpPostedFile theFile = context.Request.Files[filename];

            string UpImgType = "pdf | jpg | gif | png | jpeg";
            try
            {

                // 判断文件大小
                if (theFile.ContentLength == 0)
                {
                    error = "很抱歉,文件不能为空,请选择合适的文件!";
                }
                else if (theFile.ContentLength > 0 && theFile.ContentLength < 5000 * 1024)
                {
                    // 判断格式
                    string strEx = (ResultHelper.GetExName(theFile.FileName)).ToLower();

                    if (UpImgType.IndexOf(strEx.Replace(".", "")) < 0)
                    {
                        error = "上传文件格式不正确,正确格式为" + UpImgType + ",请您重新选择合适的文件!";
                    }

                    if (Directory.Exists(PicPath) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(PicPath);
                    }

                    tempFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + strEx;
                    newPath = PicPath + "/" + tempFileName;

                    //网页只能显示URL地址的图片
                    UrlPath = ConfigurationManager.AppSettings["imgUrl"].ToString() + "/Upload/image/" + erji + "/" + tempFileName;

                    //图片必须根据物理路径上传
                    if (File.Exists(PicPath + "/" + tempFileName)) File.Delete(PicPath + "/" + tempFileName);

                    theFile.SaveAs(PicPath + "/" + tempFileName);

                    //
                    string oldName = context.Request["oldName"];
                    oldName = oldName.Replace(ConfigurationManager.AppSettings["imgUrl"].ToString(), ConfigurationManager.AppSettings["imgWuli"].ToString());

                    if (!string.IsNullOrEmpty(oldName) && File.Exists(oldName))
                    {
                        File.Delete(oldName);
                    }
                }
                else
                {
                    error = "上传文件不能超过" + 5000.ToString() + "KB,请您重新选择合适的文件!";
                }
            }
            catch (Exception ex)
            {
                error = "很抱歉,文件上传失败,请您重试,错误信息:" + ex;
            }
            //把结果序列化成JSON,再传给前端
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string json = jss.Serialize(new { error = error, url = UrlPath });
            context.Response.Write(json);

        }

其实我这个写的很复杂,后来写的就慢慢优化了不少,特别是路径和文件名的设置部分,不过基本可以实现无刷新上传图片,效率也不错,就是图片大了的时候,会导致上传时间有点长,可以使用一个waiting的dialog模态遮罩层进行等待提示。