利用jquery.form.js实现Ajax无刷新图片上传及预览功能

某些时候当我们做登记页面的时候可能需要上传图片,并实现即时预览的功能。

如果只是预览而不上传,可以使用ImagePreview来实现,方便简单。如果需要上传,那么你也可以使用uploadify无刷新上传插件来实现,并在上传完毕后更改img标签的src路径来实现预览功能,此插件自带php实例,网上也有很多Asp.Net的实例可供参考。

好了,进入正题吧,首先附上HTML代码:

<asp:Image ID="imgexper" Width="129px" Height="172px" ImageUrl="~/images/nophoto.gif"
                    runat="server" />
<div>
     <asp:FileUpload ID="fuimg" runat="server" onchange="if(this.value)ispic(this.value,this);" />
     <asp:HiddenField ID="hfpath" runat="server" />
</div>

JS代码:

//======去除空格
String.prototype.Trim = function () {
    return this.replace(/(^s*)|(s*$)/g, "");
}
//======根据ID获取对象的值并去除空格
var $val = function (id) {
    if (typeof id == "string") {
        try {
            return document.getElementById(id).value.Trim();
        }
        catch (Error) {
            alert("ID错误!");
        }
    }
    else if (typeof id == "object") {
        try {
            return id.value.Trim();
        }
        catch (Error) {
            alert("参数错误!");
        }
    }
    else {
        alert("参数错误!");
    }
};

function ispic(file, node) {
var pic = "../images/"if (file) { var suffix = file.split("."); var num = suffix.length - 1; var name = suffix[num].toLowerCase(); if (name != "jpeg" && name != "jpg" && name != "gif" && name != "bmp" && name != "png") { alert("上传类型错误,暂只支持.jpeg|.jpg|.gif|.bmp|.png格式!"); node.outerHTML = node.outerHTML; clearphoto(pic); //清理 } else { var oldpath = $val("hfpath"); var pageurl = "ExpertPhotoAjax.aspx?oldpath=" + oldpath; var options = { url: pageurl, type: "POST", dataType: "HTML", beforeSend: function () { document.getElementById("imgexper").src = pic + "wating.gif"; }, success: function (path) { if (path != "") { var links = path.split(","); document.getElementById("hfpath").value = links[0]; document.getElementById("imgexper").src = links[1]; } else { clearphoto(pic); alert("加载失败,请重新选择图片!"); } }, error: function () { clearphoto(pic); alert("加载失败,请重新选择图片!"); } }; // 将options传给ajaxForm jQuery('#form1').ajaxSubmit(options); } } } function clearphoto(pic) { document.getElementById("hfpath").value = ""; document.getElementById("imgexper").src = pic + "noimg.gif"; }

 C#代码:

//变量定义
                 string oldpath = Request.QueryString["oldpath"].ToString();
               string path = "";
               //删除之前上传的图片
                if (oldpath != "")
                {
                    oldpath = HttpContext.Current.Server.MapPath(oldpath);
                    if (System.IO.File.Exists(oldpath))
                    {
                        System.IO.File.Delete(oldpath);
                    }
                }
                //上传新图片
                try
                {
                    HttpFileCollection files = Context.Request.Files;
                    if (files.Count > 0)
                    {
                        string photoname = DateTime.Now.ToString("yyyyMMddHHmmss");
                        HttpPostedFile file = files[0];
                        if (file.ContentLength > 0)
                        {
                            //创建目录
                            path = "~/UpFile/Photos/";
                            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
                            {
                                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
                            }
                            string fileName = file.FileName;
                            string extension = Path.GetExtension(fileName);
                            path += photoname + extension;
                            file.SaveAs(HttpContext.Current.Server.MapPath(path));
                            if (flag == 1)
                                path += path.Replace("~/", ",");
                            else
                                path += path.Replace("~", ",..");
                        }
                    }
                }
                catch (Exception)
                {
                    path = "";
                }
                Response.Write(path);
                Response.End();

 PS:使用的此方法的页面必须引用jquery.form.js

原文地址:https://www.cnblogs.com/lxc89/p/3230555.html