简单上传头像

上传头像的问题:

  1. 文件以怎样的方式进行传输?
  2. 后台怎样接收到数据并处理?

首先说怎样传输,查看了一些上传头像的博文,上传头像的格式完全取决于自己的个人意向。

格式如下:

  •  Base64格式(string的一种类型)
  • FromData数据格式(大多前端UI框架的上传方式基本都是这一种)

而上传头像的无外乎form表单的上传以及ajax上传

后台处理使用的是System.Drawing.Bitmap类进行绘画存储

上代码

  Html:

<img src="../img/tx_bg.jpg" id="pic" />
<
input id="upload" name="file" accept="image/*" type="file" style="display: none">

   js:

$("#pic").click(function () {
  $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传

})

$('#upload').on('change', function (e) {
                // 检查是否是图片
                var filePath = $(this).val(),
                    fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();//获取文件后缀名
                //检查后缀名
                if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
                    layer.msg('文件格式必须为:png/jpg/jpeg');//showError是另外写的一个显示错误信息的function
                    return;
                }

                //获取并记录图片的base64编码
                var reader = new FileReader();
                reader.readAsDataURL(e.target.files[0]); // 读出 base64
                reader.onloadend = function () {
                    // 图片的 base64 格式, 可以直接当成 img 的 src 属性值        
                    var dataURL = reader.result;//base64
                    // 显示图片
                    $('#pic').attr('src', dataURL);
                    dataURL = JSON.stringify(dataURL);
                    $.ajax({
                        url: "方法接口",
                        type: "post",
                        data: "{file:" + dataURL + " }",
                        dataType: "json",
                        cache: false,
                        contentType: "application/json",
                        success: function (data) {
                            console.log(data.d);
                        }
                    });
                };
               
            });

后台:

   [ScriptMethod(UseHttpGet = false)]
    [WebMethod(EnableSession = true, Description = "上传头像")]
    public string ChangePhoto(string file)
    {
        try
        {
            string filename = "";//声明一个string类型的相对路径

            String base64 = file.Substring(file.IndexOf(",") + 1);//将‘,’以前的多余字符串删除
            String files = file.Split(',')[0];
            files = files.Split('/')[0];
            System.Drawing.Bitmap bitmap = null;//定义一个Bitmap对象,接收转换完成的图片
            byte[] arr = Convert.FromBase64String(base64);//将纯净资源Base64转换成等效的8位无符号整形数组
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long timeStamp = (System.DateTime.Now.Ticks - startTime.Ticks) / 10000;
            MemoryStream ms = new MemoryStream(arr);//转换成无法调整大小的MemoryStream对象
            using (Bitmap bmp = new Bitmap(ms))//将MemoryStream对象转换成Bitmap对象
            {
                bitmap = bmp;
                filename = "Upload/" + timeStamp + ".png";//所要保存的相对路径及名字
                string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()); //获取程序根目录
                string imagesurl2 = tmpRootDir + filename.Replace(@"/", @"\"); //转换成绝对路径 
                bitmap.Save(imagesurl2, System.Drawing.Imaging.ImageFormat.Jpeg);//保存到服务器路径
                var json = iUC.ChangeUserPhoto(filename, Session["UserNo"].ToString());//将路径存入数据库
                return json;
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
            
    }

总的来说,这个功能来自各个博主文章的帮助,前端的js,后台的图片处理、异常的处理。。。。

我只能算是总结了大家的智慧结晶。算是站在巨人们的肩膀上瞭望了。。。。

 

posted @ 2019-09-03 11:41  脑回路神奇的肥菜鸟  阅读(300)  评论(0)    收藏  举报