asp.net微信开发(永久素材管理)
除了3天就会失效的临时素材外,开发者有时需要永久保存一些素材,届时就可以通过本接口新增永久素材。
最近更新,永久图片素材新增后,将带有url返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。
请注意:
- 1、新增的永久素材也可以在公众平台官网素材管理模块中看到
- 2、永久素材的数量是有上限的,请谨慎新增。图文消息素材和图片素材的上限为5000,其他类型为1000
- 3、素材的格式大小等要求与公众平台官网一致。具体是,图片大小不超过2m,支持bmp/png/jpeg/jpg/gif格式,语音大小不超过5m,长度不超过60秒,支持mp3/wma/wav/amr格式
- 4、调用该接口需https协议
先来看我自己自定义的后台永久素材管理效果图,如下:
再看看微信官网后台上的显示界面,同步的哦!
首先我们来分析一下步骤:
第一步:如果想让图片在自己的页面显示,首先得先建个实体类吧,用来存储素材的信息吧
/// <summary> /// 微信永久素材实体类,用于保存永久素材上传至微信服务器后返回的数据 /// </summary> 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两个字段数据和其他字段数据一并保存到本地服务器,上传的代码如下:
/// <summary> /// 上传图片至微信服务器,并且本地也保存一份 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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("<script>alert('上传图片素材成功!');location='wxsucaimannageimagelist.aspx';</script>"); } else { response.write("<script>alert('上传图片素材失败!');location='wxsucaimannageimagelist.aspx';</script>"); } } } catch(exception ex) { response.write(ex.message.tostring()); } } else { response.write("<script>alert('上传文件不能大于2m!')</script>"); } } else { response.write("<script>alert('只支持bmp,gif,png,jpg,jpeg格式的图片!')</script>"); } } else { response.write("<script>alert('请选择图片!')</script>"); } }
走到这其实效果已经出来了,接下来看最后一步就是删除选中的素材,删除微信远程服务器的数据--再删除本地服务器的数据,有人问难道这个还有顺序?
其实你可以想象,如果微信服务器的图片没有删除成功,你先把本地服务器的图片删除了,那就和官网同步不了了。
第三步:删除素材
/// <summary> /// 全选全不选 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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; } } /// <summary> /// 删除选中项 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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("<script>alert('图片素材删除成功!');location='wxsucaimannageimagelist.aspx';</script>"); } else { response.write("<script>alert('微信服务器图片删除成功!本地服务器图片素材删除失败!');location='wxsucaimannageimagelist.aspx';</script>"); } } } } } if (!ischeck) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('请先选中删除项!!!')", true); return; } }
最后是页面的代码一并奉上,大家仔细研究。
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title></title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <style type="text/css"> .meun { width:1100px; height:40px; margin-left:20px; line-height:40px; margin-top:10px;border-bottom:1px solid #d6d6d6; } .meun ul { padding:0px; margin:0px; } .meun ul li{ float:left; width:100px; text-align:center;list-style:none; } .meun ul li:hover{ border-bottom:3px solid #ecd9df; cursor:pointer; } a:hover { color:#000; } .checkedstyle { border-bottom:3px solid #208008; } .meun_imglist { width:1050px; min-height:300px; border:1px solid #d6d6d6; margin-top:20px; margin-left:35px; margin-bottom:30px; } .uploadstyle { width:300px; background-image:url('images/inputbg.gif'); background-repeat:repeat-x; height:35px; border:1px solid #d6d6d6; float:left; margin-bottom:10px; line-height:35px; } .checkall { float:left; padding:5px; } .checkin { float:left; padding:2px; } .dlsucaiimagelist { margin-top:10px; margin-left:10px; } </style> </head> <body> <form id="form1" runat="server"> <div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="welcome.aspx" target="rightframe">首页</a></li> <li>微信管理</li> <li>德桥员工服务中心--素材管理</li> </ul> </div> <div style="height:30px; line-height:30px; margin-top:10px; margin-left:45px;"><span style="float:left; font-size:16px;">素材管理</span><span style="color:red; float:left; margin-left:20px;">永久素材和微信官网同步,您在这里所操作的任何一项,将影响到官网后台素材管理,谨慎操作!</span></div> <div class="meun"> <ul> <li><a href="wxsucaimanagelist.aspx">图文消息</a></li> <li class="checkedstyle"><a href="wxsucaimannageimagelist.aspx">图片库</a></li> <li><a href="#">语音</a></li> <li><a href="#">视频</a></li> </ul> </div> <div class="meun_imglist"> <div style="margin:5px auto 10px 10px; height:36px; line-height:36px;"> <asp:fileupload id="fileuploadimage" cssclass="uploadstyle" runat="server" /> <asp:linkbutton id="linbtnuploadimg" runat="server" onclick="linbtnuploadimg_click"><span style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; margin-bottom:10px; font-weight:bold; text-align:center; float:left; margin-left:10px; color:#fff;">上传</span></asp:linkbutton> <span style="margin-left:30px; color:red;" > 支持jpg,gif,png,bmp格式图片,大小2m内,如上传成功后,图片未能显示,请将图片重新命名后再尝试上传.</span> </div> <div style=" clear:both;line-height:35px; margin:10px auto auto auto; height:35px; width:1030px; background-color:#f6f6f6; border-radius:5px; border-bottom:1px solid #d6d6d6;"> <asp:checkbox id="checkall" cssclass="checkall" autopostback="true" runat="server" oncheckedchanged="checkall_checkedchanged" /> <span style="float:left; padding:3px;">全选</span> <asp:linkbutton id="linkbtndeleteselected" runat="server" onclick="linkbtndeleteselected_click"><span style="width:111px; height:25px; line-height:25px; font-weight:bold; text-align:center; float:left; margin-left:15px; color:#000; background-color:#fff; margin-top:5px; border:1px solid #ecd9df; border-radius:3px;">删除选中</span></asp:linkbutton> </div> <asp:datalist id="dlsucaiimagelist" cssclass="dlsucaiimagelist" runat="server" repeatcolumns="6"> <itemtemplate> <div style="width:150px; height:180px; margin-right:22px;margin-bottom:15px; border:1px solid #d9d9d9;"> <img src='../weixinimg/<%# eval("sucaiurl") %>' style="height:120px; width:150px; border:0px;" /> <div style="width:150px;height:25px; line-height:25px; text-indent:3px; border-top:1px solid #d9d9d9;"> <asp:checkbox id="checkin" cssclass="checkin" runat="server" /> <asp:label id="lbsucaiurl" tooltip='<%# eval("sucaiurl")%>' runat="server" text='<%# eval("sucaiurl").tostring().length>8?eval("sucaiurl").tostring().substring(0,8)+"...":eval("sucaiurl").tostring() %>'></asp:label> </div> <div style=" clear:both; width:150px;height:25px; line-height:25px; text-indent:5px; border-top:1px solid #d9d9d9;"> <%# eval("uploaddate").tostring().length>20?eval("uploaddate").tostring().substring(0,20)+"...":eval("uploaddate").tostring() %> <asp:label id="lbsucaiid" runat="server" visible="false" text='<%# eval("sucaiid") %>'></asp:label> <asp:label id="lbmedia_id" runat="server" visible="false" text='<%# eval("media_id") %>'></asp:label> </div> </div> </itemtemplate> </asp:datalist> </div> </form> </body> </html>
其他素材上传都类似,就不一一介绍了。
新建图文素材界面如下:
从图片库选择图片素材如下:
这是就是从已上传过的图片库中选择的,和图片素材管理界面的功能基本相似,只不过多了一个确认选择的按钮,因为确认选择了之后,要关闭本页,回到新建图文页面,主要代码:
/// <summary> /// 确认选择,选中之后,跳转至新建图文页面 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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("<script>alert('已选择!');window.opener.location.reload();window.close();</script>"); } } } }
新建图文的页面在接收的时候可以这样:
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();//图片的文件名称 } }
最后新建图文信息的效果图如下:
官方后台如下:
关于编辑图文信息的关键代码如下:
/// <summary> /// 绑定事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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; } } } }
编辑提交关键代码如下:
/// <summary> /// 保存图文素材和修改按钮公用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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("<script>alert('图文素材修改成功!');location='wxsucaimanagelist.aspx';</script>"); } else { response.write("<script>alert('图文素材修改失败!');</script>"); } } } } else { //新增图文素材 } }
需注意:新建图文页面和修改图文页面是公用的一个页面.......
编辑提交按钮和保存按钮是公用的一个按钮.....
精彩专题分享:asp.net微信开发教程汇总,欢迎大家学习。
以上就是本文的全部内容,希望对大家的学习有所帮助。
上一篇: Android开发艺术探索学习笔记(七)