asp.net单步无刷新上传并回显图片

找了N多的办法,总算是解决了这个问题:

首先添加两个js库 可以自己去网上下载

<script type="text/javascript" src="/js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="/js/jquery.form.js"></script>


然后就是前台代码部分 这里把fileupload控件隐藏,

<form id="fileform" method="post">
<img id="u_img" runat="server" src="/images/t2.jpg" />
 <input type="button" class="checkimg" value="修改头像"/>
<input id="FileUpload1" name="FileUpload1" type="file" style="display:none" />
</form>

然后通过普通按钮的点击事件来触发fileupload的点击事件,再通过fileupload的change事件触发ajax到后台上传

jQuery(document).ready(function () {
        jQuery(".checkimg").click(function () {
            jQuery('#FileUpload1').click();
        });
  
        jQuery("#FileUpload1").change(function () {
            jQuery("#fileform").ajaxSubmit({
                url: "/ucenter/fileuploud.aspx?action=topimg&FileName=FileUpload1",
                dataType: 'text', //数据格式为json
                beforeSend: function () { //开始上传

                },
                success: function (data) { //成功
                    jQuery("#u_img").attr("src", data);

                },
                error: function (xhr) { //上传失败
                    //alert("上传失败");
}

/// <summary>
        /// 修改照片
        /// </summary>
        /// <param name="FileName">上传控件名name</param>
        private void checkimg(string FileName)
        {
            if (Request.Files[FileName].ContentLength > 0)
            {
                HttpPostedFile f = Request.Files[FileName];//获取控件元素

                string filename = f.FileName;//获取文件名

                string path = "/UploadFiles/" + imgname(filename);//上传地址+文件名,imgname是我自己写的文件重新命名的方法

                f.SaveAs(Server.MapPath(path));//上传文件到服务器

                try
                {
                    Response.Write(path);
                }
                catch (Exception ex) { Response.Write(ex); }

            }
            else
            {

                Response.Write("error");
            }
        }



发布了42 篇原创文章 · 获赞 4 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章