c# 微信開發 《保存圖片生成素材ID》

只有生成素材ID,圖片才能在微信中以圖片格式發出去。css

/// <summary>
        /// 獲取素材ID
        /// </summary>
        /// <param name="type"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static string GetMaterial(string type, string filepath)
        {
            string Materialpath = System.AppDomain.CurrentDomain.BaseDirectory + filepath;
            Entity Material = WeixinDA.GetMaterial(Materialpath);
            DateTime Time = Material.GetValue("OverTime").ToDateTime();
            int days = (Time - DateTime.Now).Days; //超時時間和當前時間相比
            if (days > 0)//有效期內
            {
                return Material.GetValue("MaterialID").TryString();
            }
            else
            {
                return UpMaterial(type, Materialpath);
            }
        }

 /// <summary>
        /// 上傳臨時素材,得到mediaID
        /// </summary>
        /// <param name="type">  上傳的臨時多媒體文件。格式和大小限制,以下:
        /// 圖片(image): 1M,支持JPG格式
        /// 語音(voice):2M,播放長度不超過60s,支持AMR\MP3格式
        /// 視頻(video):10MB,支持MP4格式
        /// 縮略圖(thumb):64KB,支持JPG格式。
        /// 媒體文件在後臺保存時間爲3天,即3天后media_id失效。</param>
        /// <param name="filepath"></param>
        /// <returns></returns>
///public const string Material_Url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}";
        public static string UpMaterial(string type, string filepath)
        {
            string accessToken = GetAccsss_token();
            string url = string.Format(Material_Url, accessToken, type);
            WebClient myWebClient = new WebClient();
            string MediaId = "";
            myWebClient.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                byte[] responseArray = myWebClient.UploadFile(url, "POST", filepath);
                string result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);
                MediaId = JObject.Parse(result)["media_id"].TryString();
            }
            catch (Exception ex)
            {
                FileLog.AddLog("素材MaterialError", ex.Message);
            }
            return MediaId;
        }
相關文章
相關標籤/搜索