Jquery上传图片至服务器

来源:互联网 发布:win8.1装ubuntu双系统 编辑:程序博客网 时间:2024/05/21 18:35

个人小说网站友书-绿色、纯净、无广告欢迎广大同行前来看小说

业务需求介绍:
要求点击图片便打开图片选择路径,并对选择的图片进行上传至服务器,

前端代码: <span class="user-photo" runat="server">    <img id="userImg" runat="server" onclick="uploadImg()" src="" onerror="src='../../images/timg%20(1).jpg'"> </span><asp:FileUpload ID="FileUpload1" runat="server" Style="display: none;" /> Jquery部分:function uploadImg() {            $("#FileUpload1").trigger("click");        }        $(function () {            BindUserData();            BindJF();            GetBriefData();            $("#FileUpload1").hide();            $("#FileUpload1").change(function () {                var imgUrl = $("#FileUpload1").val();                var formData = new FormData();                formData.append("action", "UpLoadUserImg");                formData.append("imgFile", $('#FileUpload1')[0].files[0]);                $.ajax({                    url: "../../../program/ashx/Hand_User.ashx",                    type: "POST",                    data: formData,                    /**                    *必须false才会自动加上正确的Content-Type                    */                    contentType: false,                    /**                    * 必须false才会避开jQuery对 formdata 的默认处理                    * XMLHttpRequest会对 formdata 进行正确的处理                    */                    processData: false,                    success: function (data) {                        if (data.status == "true") {                            //ErrorAlert("上传成功!", "../user-center/user-center.aspx");                            var aa = data.msg;                            aa = "/" + aa.substr(aa.indexOf("upload"));                            $("#userImg").attr("src", aa);                            ErrorAlert("上传成功!", "");                        }                        if (data.status == "error") {                            ErrorAlert(data.msg)                        }                        $("#imgWait").hide();                    },                    error: function () {                        ErrorAlert("上传失败!")                        $("#imgWait").hide();                    }                });            });        });一般处理程序中:    private void UpLoadUserImg(HttpContext context)        {            if (context.Request.Files.Count > 0)            {                HttpPostedFile file1 = context.Request.Files["imgFile"];                string sysDT = DateTime.Now.ToString("yyyyMMdd");                int userId = ((Sjune.Model.MemberInfo)(context.Session["qt_UserInfo"])).Id.ToInt();                uploadFile(file1, "~/upload/" + sysDT, userId);  //这里引用的是上面封装的方法                WriteJson(context.Response, "true", ImgUrls);            }            else            {                WriteJson(context.Response, "error", "请选择要上传的文件");            }        }         public static void WriteJson(HttpResponse response, string status1, string msg1, object data1 = null)        {            response.ContentType = "application/json";            var obj = new { status = status1, msg = msg1, data = data1 };            string json = new JavaScriptSerializer().Serialize(obj);            response.Write(json);        }        public static void uploadFile(HttpPostedFile file, string virpath, int userId)        {            if (file.ContentLength > 1024 * 1024 * 6)            {                throw new Exception("文件不能大于6M");            }            string imgtype = Path.GetExtension(file.FileName);            //imgtype对上传的文件进行限制            if (imgtype != ".jpg" && imgtype != ".jpeg" && imgtype != ".bmp" && imgtype != ".gif")            {                throw new Exception("只允许上传jpg、bmp、gif....文件");            }            string dirFullPath = HttpContext.Current.Server.MapPath(virpath);            if (!Directory.Exists(dirFullPath))//如果文件夹不存在,则先创建文件夹            {                Directory.CreateDirectory(dirFullPath);            }            string imgName = System.Guid.NewGuid().ToString();            string imgUrl = dirFullPath + "/" + imgName + imgtype;            file.SaveAs(imgUrl);            ImgUrls = imgUrl;            Model.MemberInfo db_model = new BLL.MemberInfo().GetModel(userId);            imgUrl = imgUrl.Substring(imgUrl.LastIndexOf(@"\upload"));            db_model.MemberLogo = imgUrl;            new BLL.MemberInfo().Update(db_model);        }

如有问题,请加我QQ:631931078或13501715983 至于验证答案么,是个搞IT的都知道