• C# Flash 图片上传案例(结合网上腾讯头像上传Flash插件)


    之前遇到过很多次要上传类似头像图片这种功能需求,这次是要求弄一个flash插件上传图片

    感谢主,一个偶然机会在网上找到了一个很好的腾讯头像修改的flash插件:插件下载

    这个功能采用Ajax访问支持,具体实现方法如下:

    1.新建一个Ajax.ashx页面,代码如下:

    <%@ WebHandler Language="C#" Class="Ajax" %>
    
    using System;
    using System.Web;
    using System.IO;
    
    public class Ajax : IHttpHandler
    {
    
        public void ProcessRequest(HttpContext context)
        {
            string uid = context.Request.QueryString["input"];
            if (!string.IsNullOrEmpty(context.Request["Filename"]) && !string.IsNullOrEmpty(context.Request["Upload"]))
            {
                ResponseText(UploadTempAvatar(uid));
            }
            if (!string.IsNullOrEmpty(context.Request["avatar1"]) && !string.IsNullOrEmpty(context.Request["avatar2"]) && !string.IsNullOrEmpty(context.Request["avatar3"]))
            {
                CreateDir(uid);
                if (!(SaveAvatar("avatar1", uid) && SaveAvatar("avatar2", uid) && SaveAvatar("avatar3", uid)))
                {
                    File.Delete(GetMapPath("idcardphotos\upload\idcardphoto\" + uid + ".jpg"));
                    ResponseText("<?xml version="1.0" ?><root><face success="0"/></root>");
                    return;
                }
                File.Delete(GetMapPath("idcardphotos\upload\idcardphoto\" + uid + ".jpg"));
                ResponseText("<?xml version="1.0" ?><root><face success="1"/></root>");
                return;
            }
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    
        private void CreateDir(string uid)
        {
            string avatarDir = string.Format("idcardphotos/upload/idcardphoto/{0}",
                 uid);
            if (!Directory.Exists(GetMapPath(avatarDir)))
                Directory.CreateDirectory(GetMapPath(avatarDir));
        }
    
        private void ResponseText(string text)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(text);
            HttpContext.Current.Response.End();
        }
    
        private string UploadTempAvatar(string uid)
        {
            string filename = uid + ".jpg";
            string uploadUrl = GetRootUrl("User/idcardphotos/") + "upload/idcardphoto";
            string uploadDir = GetMapPath("idcardphotos\upload\idcardphoto");
            if (!Directory.Exists(uploadDir + "temp\"))
                Directory.CreateDirectory(uploadDir + "temp\");
    
            filename = "temp/" + filename;
            if (HttpContext.Current.Request.Files.Count > 0)
            {
                HttpContext.Current.Request.Files[0].SaveAs(uploadDir + filename);
            }
    
            return uploadUrl + filename;
        }
    
        private byte[] FlashDataDecode(string s)
        {
            byte[] r = new byte[s.Length / 2];
            int l = s.Length;
            for (int i = 0; i < l; i = i + 2)
            {
                int k1 = ((int)s[i]) - 48;
                k1 -= k1 > 9 ? 7 : 0;
                int k2 = ((int)s[i + 1]) - 48;
                k2 -= k2 > 9 ? 7 : 0;
                r[i / 2] = (byte)(k1 << 4 | k2);
            }
            return r;
        }
    
        private bool SaveAvatar(string avatar, string uid)
        {
            byte[] b = FlashDataDecode(HttpContext.Current.Request[avatar]);
            if (b.Length == 0)
                return false;
            string size = "";
            if (avatar == "avatar1")
                size = "large";
            else if (avatar == "avatar2")
                size = "medium";
            else
                size = "small";
            string avatarFileName = string.Format("idcardphotos/upload/idcardphoto/{0}/{1}.jpg",
                uid, size);
            FileStream fs = new FileStream(GetMapPath(avatarFileName), FileMode.Create);
            fs.Write(b, 0, b.Length);
            fs.Close();
            return true;
        }
    
        public static string GetRootUrl(string forumPath)
        {
            string ApplicationPath = HttpContext.Current.Request.ApplicationPath != "/" ? HttpContext.Current.Request.ApplicationPath : string.Empty;
            int port = HttpContext.Current.Request.Url.Port;
            return string.Format("{0}://{1}{2}{3}/{4}",
                                 HttpContext.Current.Request.Url.Scheme,
                                 HttpContext.Current.Request.Url.Host,
                                 (port == 80 || port == 0) ? "" : ":" + port,
                                 ApplicationPath,
                                 forumPath);
        }
    
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\");
                if (strPath.StartsWith("\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\', 1)).TrimStart('\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
    }
    选择图片和上传图片时要调用的Ajax处理页面

    用来处理选择以及图片编辑完成之后保存到服务器的图片目录下;

    2.前台调用flash插件代码:

    <script language="javascript" type="text/javascript">
            $(function (id) {
                var flashParam = '<%=avatarFlashParam %>';
                var HeadImg = '<%=this.HeadImg %>';
                $("#imgHead").attr("src", HeadImg);
                $("#aH").click(function () {
                    $("#avatarctr1").show();
                    $("#avatarctr1").html(AC_FL_RunContent('width', '540', 'height', '253', 'scale', 'exactfit', 'src', flashParam, 'imgHead', 'mycamera', 'name', 'mycamera', 'quality', 'high', 'bgcolor', '#ffffff', 'wmode', 'transparent', 'menu', 'false', 'swLiveConnect', 'true', 'allowScriptAccess', 'always'));
                });
    
                return document.getElementById(id);
            });
    
            //修改头像
            function Upload() {
                var imgHead = $("#imgHead").attr("src");
    
                if (null != imgHead && imgHead != "<%=Localhost %>/User/idcardphotos/head.png")
                    $("#btnUpload").click();
                else {
                    alert("请先上传头像图片!");
                    return false;
                }
            }
    
            var userAgent = navigator.userAgent.toLowerCase();
            var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
            var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
            var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
            var is_mac = userAgent.indexOf('mac') != -1;
            function AC_GetArgs(args, classid, mimeType) {
                var ret = new Object();
                ret.embedAttrs = new Object();
                ret.params = new Object();
                ret.objAttrs = new Object();
                for (var i = 0; i < args.length; i = i + 2) {
                    var currArg = args[i].toLowerCase();
                    switch (currArg) {
                        case "classid": break;
                        case "pluginspage": ret.embedAttrs[args[i]] = 'http://www.macromedia.com/go/getflashplayer'; break;
                        case "src": ret.embedAttrs[args[i]] = args[i + 1]; ret.params["movie"] = args[i + 1]; break;
                        case "codebase": ret.objAttrs[args[i]] = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'; break;
                        case "onafterupdate": case "onbeforeupdate": case "onblur": case "oncellchange": case "onclick": case "ondblclick": case "ondrag": case "ondragend":
                        case "ondragenter": case "ondragleave": case "ondragover": case "ondrop": case "onfinish": case "onfocus": case "onhelp": case "onmousedown":
                        case "onmouseup": case "onmouseover": case "onmousemove": case "onmouseout": case "onkeypress": case "onkeydown": case "onkeyup": case "onload":
                        case "onlosecapture": case "onpropertychange": case "onreadystatechange": case "onrowsdelete": case "onrowenter": case "onrowexit": case "onrowsinserted": case "onstart":
                        case "onscroll": case "onbeforeeditfocus": case "onactivate": case "onbeforedeactivate": case "ondeactivate": case "type":
                        case "id": ret.objAttrs[args[i]] = args[i + 1]; break;
                        case "width": case "height": case "align": case "vspace": case "hspace": case "class": case "title": case "accesskey": case "name":
                        case "tabindex": ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i + 1]; break;
                        default: ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i + 1];
                    }
                }
                ret.objAttrs["classid"] = classid;
                if (mimeType) {
                    ret.embedAttrs["type"] = mimeType;
                }
                return ret;
            }
            function AC_FL_RunContent() {
                $("#hid").val("0");
                var ret = AC_GetArgs(arguments, "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
                var str = '';
                if (is_ie && !is_opera) {
                    str += '<object ';
                    for (var i in ret.objAttrs) {
                        str += i + '="' + ret.objAttrs[i] + '" ';
                    }
                    str += '>';
                    for (var i in ret.params) {
                        str += '<param name="' + i + '" value="' + ret.params[i] + '" /> ';
                    }
                    str += '</object>';
                } else {
                    str += '<embed ';
                    for (var i in ret.embedAttrs) {
                        str += i + '="' + ret.embedAttrs[i] + '" ';
                    }
                    str += '></embed>';
                }
                return str;
            }
        </script>
    加载flash插件的javascript,兼容各主流浏览器

    3.前台显示图片修改控件:

    <div id="divUnVerify" class="VipVerify_Con VV_rz">
                    <ul style="height: auto;">
                        <li class="left">当前头像:</li>
                        <li class="right" style="height: auto;">
                            <img id="imgHead" runat="server" />
                            <a id="aH" href="javascript:;" class="a1">点击更改</a> </li>
                        <li id="avatarctr1" style="display: none; height: auto;" class="right"></li>
                        <asp:HiddenField  ID="hidH" runat="server"/>
                        <asp:HiddenField  ID="hid" runat="server"/>
                    </ul>
                    <script type="text/javascript">
                        function updateavatar(sender, args) {
                            $("#imgHead").attr("src", "<%=Localhost %>/User/idcardphotos/upload/idcardphoto/<%=tname %>/medium.jpg?random=1" + Math.random());
    
                            $("#hidH").val($("#hid").val() == "0" ? '<%=tname %>' : '<%=this.HeadFile %>');
                            $("#avatarctr1").hide();
                        }
                        updateavatar();
                        </script>
                    <div class="Sub_but">
                        <input type="submit" value="确  认" onclick="return Upload();" />
                        
                        <asp:Button ID="btnUpload"
                            runat="server" OnClick="btnUpload_Click" Style="display: none;" /></div>
                </div>
    显示当前头像和修改按钮,用于预览和触发修改图片的操作

    4.后台页面加载次绑定并指定Ajax调用目录:

             /// <summary>
             /// 绑定身份证上传控件
          /// </summary>
            public void BindPhotoControl()
            {
                int port = HttpContext.Current.Request.Url.Port;
                string ApplicationPath = HttpContext.Current.Request.ApplicationPath != "/" ? HttpContext.Current.Request.ApplicationPath : string.Empty;
    
                tname = DateTime.Now.ToString("yyyyMMddHHmmss") + "H";
    
                Localhost = string.Format("{0}://{1}{2}{3}",
                                     HttpContext.Current.Request.Url.Scheme,
                                     HttpContext.Current.Request.Url.Host,
                                     (port == 80 || port == 0) ? "" : ":" + port,
                                     ApplicationPath);
                EncodeLocalhost = HttpUtility.UrlEncode(Localhost);
    
                avatarFlashParam = string.Format("{0}/User/idcardphotos/common/camera.swf?nt=1&inajax=1&appid=1&input={1}&ucapi={2}/User/Ajax/PhotoAjax.ashx", Localhost, tname, EncodeLocalhost);
    
               
            }
    绑定图片上传控件

    5.需要前台绑定的属性:

    /// <summary>
            /// 会员编号
            /// </summary>
            public int UserID
            {
                get
                {
                    return int.Parse(Request.QueryString["uid"].ToString());
                }
            }
    
            /// <summary>
            /// 会员当前头像详细路径
            /// </summary>
            public string HeadImg
            {
                get
                {
                    user.UserID = 0;
                    user.HeadImg = string.Empty;
                    user = BLL.HSSM_Public_DB.ModelToSqlOne<Model.Users>(user,
                        string.Format(" UserID={0}", UserID));
                    return string.IsNullOrEmpty(user.HeadImg) ? (Localhost + "/User/idcardphotos/head.png") : (Localhost + "/User/idcardphotos/upload/idcardphoto/" + user.HeadImg + "/medium.jpg");
                }
            }
    
            /// <summary>
            /// 会员当前头像文件夹名
            /// </summary>
            public string HeadFile
            {
                get
                {
                    user.UserID = 0;
                    user.HeadImg = string.Empty;
                    user = BLL.HSSM_Public_DB.ModelToSqlOne<Model.Users>(user,
                        string.Format(" UserID={0}", UserID));
                    return user.HeadImg;
                }
            }
    属性,用于前台加载时绑定

    6.最终保存图片数据的方法:

     /// <summary>
            /// 保存头像
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void btnUpload_Click(object sender, EventArgs e)
            {
                user.UserID = 0;
                user.HeadImg=string.Empty;
                user = BLL.HSSM_Public_DB.ModelToSqlOne<Model.Users>(user,
                    string.Format(" UserID={0}", UserID));
                user.HeadImg=hidH.Value.Trim();
    
                int IsSuccess = BLL.HSSM_Public_DB.AlterTable<Model.Users>(user);
    
                if (IsSuccess > 0)
                {
                    string url = "http://" + Request.ServerVariables["HTTP_HOST"] + "/User/UserSetup.aspx?uid=" + UserID;
                    Response.Redirect(url);//跳转到会员安全认证信息页面
                }
                else
                    ClientScript.RegisterStartupScript("".GetType(), "", "<script language="javascript" type="text/javascript">alert('修改失败!');</script>");
            }
    View Code

    效果图:

    未修改之前的头像:

    点击“点击更改”之后弹出图片选择按钮:

    选择图片之后进行选择编辑,然后点击“确定”

    点击“完成”:

    修改成功!

  • 相关阅读:
    洛谷P2737 [USACO4.1]麦香牛块Beef McNuggets(DP,裴蜀定理)
    洛谷P4924 魔法少女小Scarlet
    洛谷P3912 素数个数
    洛谷P4016 负载平衡问题(费用流)
    洛谷P2736 [USACO3.4]“破锣摇滚”乐队 Raucous Rockers
    母函数(生成函数)
    洛谷P4086 [USACO17DEC]My Cow Ate My Homework S
    洛谷P5097 [USACO04OPEN]Cave Cows 2(ST表)
    洛谷P2713 罗马游戏(左偏树)
    洛谷P1260 工程规划
  • 原文地址:https://www.cnblogs.com/gawking/p/3495429.html
Copyright © 2020-2023  润新知