除了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 = post; 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微信开发教程汇总,欢迎大家学习。
以上就是本文的全部内容,希望对大家的学习有所帮助。