C# 微信永久素材
微信公众号自定义菜单media_id 类型需要永久素材图片,
- 永久图片素材新增后,将带有url返回给开发者,开发者可以在腾讯系域名内使用。
- 公众号的素材库保存数量有上限:图文消息素材、图片素材上限为100000,其他类型为1000。
这里只写新增图片素材接口:
http请求方式:POST,https https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE (使用curl命令,用FORM表单方式新增一个其他类型的永久素材,curl命令的使用请自行查阅资料)
需要的参数:
参数 | 是否必须 | 说明 |
---|---|---|
access_token | 是 | 调用接口凭证(注意时效性) |
type | 是 | 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) |
media | 是 | form-data中媒体文件标识,有filename、filelength、content-type等信息 |
返回的参数:
参数 | 描述 |
---|---|
media_id | 新增的永久素材的media_id |
url | 新增的图片素材的图片URL(仅新增图片素材时会返回该字段) |
这个media_id就是公众号自定义菜单图片所需要的。
上传新的素材:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btn_save" runat="server" Text="保 存" CssClass="btn btn-blue shiny" OnClick="btn_save_Click"/>
<asp:Label ID="Label1" runat="server" ForeColor="Red"></asp:Label>
//上传素材
protected void btn_save_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile.FileName == "")
{
string nr = "请选择需要上传的图片!";
this.Label1.Text = nr;
this.btn_save.Enabled = true;
}
else
{
StringBuilder files = new StringBuilder();
String path = Server.MapPath("~/CDR/");
string extention = Path.GetExtension(this.FileUpload1.PostedFiles[0].FileName).ToLower();
if (extention != ".jpg" && extention != ".png" && extention != ".png" && extention != ".gif")
{
this.Label1.Text = "允许上传的图片格式为jpg、jpeg、png和gif类型!";
return;
}
if (this.FileUpload1.PostedFiles[0].ContentLength > 4194304)
{
this.Label1.Text = "上传的图片不允许超过4MB!";
return;
}
string picname = DateTime.Now.ToString("yyyyMMddHHmmssfff") + extention;
files.Append(picname);
System.Drawing.Image image = System.Drawing.Image.FromStream(this.FileUpload1.PostedFiles[0].InputStream);
bool flag = Utils.SaveImageForSpecifiedQuality(image, path + picname, 90);
//将图片保存到文件内,
if (flag == false)
{
this.Label1.Text = "保存失败";
return;
}
string headimage = "绝对路径/CDR/" + files.ToString();
string media = WxHttpRequest.UploadMultimedia("image", headimage);
//将返回的json分成media_id 和url
string media_id = GetJsonValue(media, "media_id");
int i = SqlHelp.ExecuteSql("insert into wx_media(media_id,img,addTime) values('" + media_id + "','CDRImg/" + files.ToString() + "','" + DateTime.Now + "')");
if (i > 0)
{
this.Label1.Text = "图片上传成功";
}
return;
}
}
#region 微信永久素材上传
/// <summary>
/// 微信永久素材上传
/// </summary>
/// <param name="type">媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)</param>
/// <param name="file">上传文件的绝对路径</param>
/// <returns></returns>
public static string UploadMultimedia(string type, string file)
{
string fileName = file;
string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + IsExistAccess_Token() + "&type=" + type);
FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read);
byte[] fileByte = new byte[fs.Length];
fs.Read(fileByte, 0, fileByte.Length);
fs.Close();
//设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X");//随机分割线
request.ContentType = "multipart/form-data;charset=utf-8;boundary="+ boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("
--"+boundary+"
");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("
--" + boundary + "--
");
StringBuilder sbHeader =
new StringBuilder(
string.Format(
"Content-Disposition:form-data;name="media";filename="{0}"
Content-Type:application/octet-stream
",
fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes,0,itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(fileByte, 0, fileByte.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
string content = sr.ReadToEnd();
return content;
}
#endregion