除了3天就会失效的临时素材外,开发者有时需要永久保存一些素材,届时就可以通过本接口新增永久素材。
最近更新,永久图片素材新增后,将带有URL返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。
请注意:
1、新增的永久素材也可以在公众平台官网素材管理模块中看到
2、永久素材的数量是有上限的,请谨慎新增。图文消息素材和图片素材的上限为5000,其他类型为1000
3、素材的格式大小等要求与公众平台官网一致。具体是,图片大小不超过2M,支持bmp/png/jpeg/jpg/gif格式,语音大小不超过5M,长度不超过60秒,支持mp3/wma/wav/amr格式
4、调用该接口需https协议
先来看我自己自定义的后台永久素材管理效果图,如下:
////// 微信永久素材实体类,用于保存永久素材上传至微信服务器后返回的数据 /// public class WxSuCaiInfo { public int SuCaiId { get; set; }//自增列序号 public string SuCaiUrl { get; set; }// 存储文件名 public string SuCaiType { get; set; }//素材类型,可分为image,voice,video,thumb(缩略图) public string SuCaiTitle { get; set; }//图文消息的标题 public string SuCaiDigest { get; set; }//图文消息的摘要 public string SuCaiauthor { get; set; }//图文消息的作者 public string SuCaishow_cover_pic { get; set; }//图文消息是否显示封面.保存0或1 public string SuCaicontent { get; set; }//图文消息的正文内容 public string SuCaicontent_source_url { get; set; }//图文消息的原文链接 public string media_ID { get; set; }//上传至微信服务器后,返回的永久mediaID public string Url { get; set; }//上传至微信服务器后,返回的图片URL,仅图片才会返回此属性 public string uploadDate { get; set; }//上传日期时间 }
第二步:上传图片至微信服务器,成功后将返回的media_id和url两个字段数据和其他字段数据一并保存到本地服务器,上传的代码如下:
////// 上传图片至微信服务器,并且本地也保存一份 /// /// /// protected void LinBtnUploadImg_Click(object sender, EventArgs e) { if (this.FileUploadImage.HasFile) { string fileContentType = FileUploadImage.PostedFile.ContentType; if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/png" || fileContentType == "image/x-png" || fileContentType == "image/jpeg" || fileContentType == "image/pjpeg") { int fileSize = this.FileUploadImage.PostedFile.ContentLength; if (fileSize <= 2097152) { string fileName = this.FileUploadImage.PostedFile.FileName; // 客户端文件路径 string filepath = FileUploadImage.PostedFile.FileName; //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg //string filepath = FileUpload1.FileName; //得到上传的文件名20022775_m.jpg string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg string serverpath = Server.MapPath("~/WeiXinImg/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg //把图片上传至本地服务器 this.FileUploadImage.PostedFile.SaveAs(serverpath);//将上传的文件另存为 //上传图片素材至微信服务器,永久保存 WeiXinServer wxs = new WeiXinServer(); ///从缓存读取accesstoken string Access_token = Cache["Access_token"] as string; if (Access_token == null) { //如果为空,重新获取 Access_token = wxs.GetAccessToken(); //设置缓存的数据7000秒后过期 Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration); } string Access_tokento = Access_token.Substring(17, Access_token.Length - 37); string url = string.Format("http://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}", Access_tokento,"image"); try { string res = HttpUploadFile(url, serverpath); //判断res结果集里面是否包含media_id if (res.Contains("media_id")) { //如果能进行到这里,那说明图片已经上传至微信服务器,是永久素材哦, //开始解析json串,使用前需要引用Newtonsoft.json.dll文件 JObject jsonObj = JObject.Parse(res); //图片上传成功后,返回的是两个字段,media_id和url //将两个字段开始存入数据库,保存数据,方便获取列表的时候直接从本地服务器读取 WxSuCaiInfo wsc = new WxSuCaiInfo(); wsc.SuCaiUrl = filename;//注意,这里保存的图片名称 wsc.SuCaiType = "image";//文件类型 wsc.media_ID = jsonObj["media_id"].ToString();//这个属性保存的是微信返回的media_id wsc.Url = jsonObj["url"].ToString();//这个属性保存的才是微信返回的url wsc.uploadDate = System.DateTime.Now.ToString();//记录当前文件上传日期时间 //存入数据库 WxSuCaiService wscs = new WxSuCaiService(); int num = wscs.AddWxSuCaiInfo(wsc); if (num > 0) { Response.Write(""); } else { Response.Write(""); } } } catch(Exception ex) { Response.Write(ex.Message.ToString()); } } else { Response.Write(""); } } else { Response.Write(""); } } else { Response.Write(""); } }
走到这其实效果已经出来了,接下来看最后一步就是删除选中的素材,删除微信远程服务器的数据--再删除本地服务器的数据,有人问难道这个还有顺序?
其实你可以想象,如果微信服务器的图片没有删除成功,你先把本地服务器的图片删除了,那就和官网同步不了了。
第三步:删除素材
////// 全选全不选 /// /// /// protected void CheckAll_CheckedChanged(object sender, EventArgs e) { foreach (DataListItem item in this.DLSuCaiImageList.Items) { CheckBox checkIn = item.FindControl("CheckIn") as CheckBox; checkIn.Checked = CheckAll.Checked; } } ////// 删除选中项 /// /// /// protected void LinkBtnDeleteSelected_Click(object sender, EventArgs e) { Boolean ischeck = false; foreach (DataListItem item in this.DLSuCaiImageList.Items) { CheckBox checkIn = item.FindControl("CheckIn") as CheckBox; if (checkIn.Checked) { ischeck = true; Label lbSuCaiId = item.FindControl("lbSuCaiId") as Label; Label lbSuCaiUrl = item.FindControl("lbSuCaiUrl") as Label; Label lbmedia_ID = item.FindControl("lbmedia_ID") as Label; //删除微信服务器上的图片 WeiXinServer wxs = new WeiXinServer(); string res = ""; ///从缓存读取accesstoken string Access_token = Cache["Access_token"] as string; if (Access_token == null) { //如果为空,重新获取 Access_token = wxs.GetAccessToken(); //设置缓存的数据7000秒后过期 Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration); } string Access_tokento = Access_token.Substring(17, Access_token.Length - 37); string posturl = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=" + Access_tokento; //POST数据例子: POST数据例子:{"media_id":MEDIA_ID} string media_id = lbmedia_ID.Text.ToString(); string postData = "{\"media_id\":\"" + media_id + "\"}"; res = wxs.GetPage(posturl, postData); if (res.Contains("errcode")) { //开始解析json串,使用前需要引用Newtonsoft.json.dll文件 JObject jsonObj = JObject.Parse(res); if (jsonObj["errcode"].ToString().Equals("0")) { ///获取本地服务器的路径 string serverPathss = Server.MapPath("~/WeiXinImg/") + lbSuCaiUrl.Text.ToString(); //验证本地服务的路径是否存在该图片 if (File.Exists(serverPathss)) { //如果存在就删除 File.Delete(serverPathss); } WxSuCaiService wscs = new WxSuCaiService(); //通过media_id删除本地服务器数据库记录 int num = wscs.DeleteWxSuCaiInfo(lbmedia_ID.Text.ToString()); if (num > 0) { Response.Write(""); } else { Response.Write(""); } } } } } if (!ischeck) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请先选中删除项!!!')", true); return; } }
最后是页面的代码一并奉上,大家仔细研究。
其他素材上传都类似,就不一一介绍了。
新建图文素材界面如下:
////// 确认选择,选中之后,跳转至新建图文页面 /// /// /// protected void LinkBtnSubMitSelected_Click(object sender, EventArgs e) { Boolean bools = false; int num = 0; foreach (DataListItem item in this.DLSuCaiImageList.Items) { CheckBox checkIn = item.FindControl("CheckIn") as CheckBox; if (checkIn.Checked) { num += 1; bools = true; } } if (!bools) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请选择一个图片素材!!!')", true); return; } if (num >= 2) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('您只能选择一个图片素材!');", true); return; } else { foreach (DataListItem item in this.DLSuCaiImageList.Items) { CheckBox checkIn = item.FindControl("CheckIn") as CheckBox; if (checkIn.Checked) { ///获取选中图片media_id Label lbmedia_ID = item.FindControl("lbmedia_ID") as Label; Session["imgmedia_id"] = lbmedia_ID.Text.ToString(); Response.Write(""); } } } }
新建图文的页面在接收的时候可以这样:
if (Session["imgmedia_id"] != null) { WxSuCaiService wscs = new WxSuCaiService(); WxSuCaiInfo wscinfo = wscs.GetWxSuCaiInfo(Session["imgmedia_id"].ToString()); if(wscinfo!=null) { this.ImgTuWen.ImageUrl = "~/WeiXinImg/" + wscinfo.SuCaiUrl.ToString(); this.ImgTuWen2.ImageUrl = "~/WeiXinImg/" + wscinfo.SuCaiUrl.ToString(); this.ImgTuWen2.Visible = true; Session["imgmedia_id"] = wscinfo.media_ID.ToString();//图片的media_id Session["fileNameimg"] = wscinfo.SuCaiUrl.ToString();//图片的文件名称 } }
最后新建图文信息的效果图如下:
////// 绑定事件 /// /// /// protected void DLMpNewsList_ItemDataBound(object sender, DataListItemEventArgs e) { if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem) { LinkButton LinkBtnDeleteSucai = e.Item.FindControl("LinkBtnDeleteSucai") as LinkButton; LinkBtnDeleteSucai.Attributes.Add("OnClick","return confirm('您确定删除该图文素材???删除后将和微信官网同步删除!!')"); HyperLink HyperLinkEdit = e.Item.FindControl("HyperLinkEdit") as HyperLink; HyperLinkEdit.Attributes.Add("OnClick", "return confirm('即将进入编辑模式!!是否执行下一步操作??')"); Label lbmedia_ID = e.Item.FindControl("lbmedia_ID") as Label; HyperLinkEdit.NavigateUrl = "WxNewTuWen.aspx?media_id=" + lbmedia_ID.Text.ToString();//把图文消息的media_id传参到新建图文界面 } }
if(!Page.IsPostBack) { ///编辑模式 if (Request.QueryString["media_id"] != null) { string media_id = Request.QueryString["media_id"].ToString(); Session["sucaimedia_id"] = media_id; WxSuCaiService wscs = new WxSuCaiService(); WxSuCaiInfo wscinfo = wscs.GetWxSuCaiInfo(media_id); if (wscinfo != null) { this.txttuwen_title.Value = wscinfo.SuCaiTitle.ToString(); if (wscinfo.SuCaiTitle.ToString().Length > 15) { this.biaoti_yulan.InnerText = wscinfo.SuCaiTitle.ToString().Substring(0, 15) + "..."; } else { this.biaoti_yulan.InnerText = wscinfo.SuCaiTitle.ToString(); } this.txttuwen_author.Value = wscinfo.SuCaiauthor.ToString(); this.txtzhaiyao.InnerText = wscinfo.SuCaiDigest.ToString(); this.ImgTuWen.ImageUrl = "~/WeiXinImg/" + wscinfo.SuCaiUrl.ToString(); this.ImgTuWen2.ImageUrl = "~/WeiXinImg/" + wscinfo.SuCaiUrl.ToString(); this.ImgTuWen2.Visible = true; Session["imgmedia_id"] = wscinfo.SuCaithumb_media_id.ToString(); this.LinkBtnDeleteImg.Visible = true; if (!String.IsNullOrWhiteSpace(wscinfo.SuCaicontent_source_url.ToString())) { this.txtYuanWenUrl.Text = wscinfo.SuCaicontent_source_url.ToString(); this.txtYuanWenUrl.Visible = true; this.CheckYuanWen.Checked = true; } this.txtYuanWenUrl.Text = wscinfo.SuCaicontent_source_url.ToString(); this.tbContent.InnerText = wscinfo.SuCaicontent.ToString(); if (wscinfo.SuCaishow_cover_pic.ToString().Equals("1")) { this.CheckFengMianShow.Checked = true; } else { this.CheckFengMianShow.Checked = false; } } } }
////// 保存图文素材和修改按钮公用 /// /// /// protected void LinkBtnSaveYongjiu_Click(object sender, EventArgs e) { //非空验证 if (String.IsNullOrWhiteSpace(this.txttuwen_title.Value.ToString())) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请输入图文标题!');", true); return; } if (this.ImgTuWen2.ImageUrl.ToString().Equals("")) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('必须上传一张图片!');", true); return; } if (String.IsNullOrWhiteSpace(this.tbContent.InnerText.ToString())) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请输入正文内容!');", true); return; } //对各项进行赋值 WeiXinServer wxs = new WeiXinServer(); ///从缓存读取accesstoken string Access_token = Cache["Access_token"] as string; if (Access_token == null) { //如果为空,重新获取 Access_token = wxs.GetAccessToken(); //设置缓存的数据7000秒后过期 Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration); } string Access_tokento = Access_token.Substring(17, Access_token.Length - 37); //根据session判断media_id是否为空,也可根据request.queryString["media_id"]进行判断是否为空 if (Session["sucaimedia_id"] != null) { //执行更新操作 //{ // "media_id":MEDIA_ID, // "index":INDEX, // "articles": { // "title": TITLE, // "thumb_media_id": THUMB_MEDIA_ID, // "author": AUTHOR, // "digest": DIGEST, // "show_cover_pic": SHOW_COVER_PIC(0 / 1), // "content": CONTENT, // "content_source_url": CONTENT_SOURCE_URL // } //} string isshow_cover_pic = ""; if (this.CheckFengMianShow.Checked) { isshow_cover_pic = "1"; } else { isshow_cover_pic = "0"; } string description = NoHTML(this.tbContent.InnerText.ToString()); string postData = "{\"media_id\":\"" + Session["sucaimedia_id"].ToString() + "\",\"index\":\"0\" ,\"articles\":{\"title\":\"" + this.txttuwen_title.Value.ToString() + "\",\"thumb_media_id\":\"" + Session["imgmedia_id"].ToString() + "\",\"author\":\"" + this.txttuwen_author.Value.ToString() + "\",\"digest\":\"" + this.txtzhaiyao.InnerText.ToString() + "\",\"show_cover_pic\":\"" + isshow_cover_pic + "\",\"content\":\"" + description + "\",\"content_source_url\":\"" + this.txtYuanWenUrl.Text.ToString() + "\"}}"; ///修改永久图文素材 string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/update_news?access_token={0}", Access_tokento); string jsonres = PostUrl(url, postData); if (jsonres.Contains("errcode")) { //使用前需要引用Newtonsoft.json.dll文件 JObject jsonObj = JObject.Parse(jsonres); if (jsonObj["errcode"].ToString().Equals("0")) { //修改本地数据 //保存数据,方便获取列表的时候直接从本地服务器读取 WxSuCaiInfo wsc = new WxSuCaiInfo(); wsc.SuCaiUrl = Session["fileNameimg"].ToString();//注意,这里保存的图片名称 wsc.SuCaiTitle = this.txttuwen_title.Value.ToString();//图文消息的标题 wsc.SuCaiDigest = this.txtzhaiyao.InnerText.ToString();//图文消息的摘要 wsc.SuCaithumb_media_id = Session["imgmedia_id"].ToString();//图文的消息封面media_id wsc.SuCaiauthor = this.txttuwen_author.Value.ToString(); wsc.SuCaishow_cover_pic = isshow_cover_pic; wsc.SuCaicontent = description; wsc.SuCaicontent_source_url = this.txtYuanWenUrl.Text.ToString(); wsc.uploadDate = System.DateTime.Now.ToString();//记录当前文件保存图文素材日期时间 //修改数据库信息 WxSuCaiService wscs = new WxSuCaiService(); int num = wscs.UpdateWxSuCaiInfo(Session["sucaimedia_id"].ToString(), wsc); if (num > 0) { Session["sucaimedia_id"] = null; Response.Write(""); } else { Response.Write(""); } } } } else { //新增图文素材 } }
需注意:新建图文页面和修改图文页面是公用的一个页面.......
编辑提交按钮和保存按钮是公用的一个按钮.....
精彩专题分享:ASP.NET微信开发教程汇总,欢迎大家学习。
以上就是本文的全部内容,希望对大家的学习有所帮助。
以上就是asp.net微信开发中永久素材管理介绍的详细内容,更多请关注其它相关文章!