三、新增临时素材

三、新增临时素材

1.官方文档

       公众号在发送信息时,可能会用到一些临时的多媒体信息,对多媒体文件、多媒体信息获取和调用等操作,是通过media_id来进行的,通过新增临时素材接口,可以上传多媒体文件。

       注:临时素材只能在微信服务器保存三天,所以在使用临时素材之前应该先判断临时素材是否有效

1.1接口调用说明

调用此接口,要求使用post方式且必须为https协议,这里文档推荐我们是curl命令行工具模拟表单post,我们考虑到安全性(服务器里调用exe程序是非安全的且可能没有权限),这里我们还是使用webrequest模拟表单向微信接口发出post请求

​1.2接口返回说明

文件上传成功后,返回上传的文件类型、媒体文件上传时间戳,以及最重要的media_id,我们可以将这些信息存入数据库中,当要使用时,从数据库取出,先通过create_at字段判断文件是否过期,在进行后续操作

2.开发应用:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//1.定义接口url
 
 
//2.发送带文件流的数据post到微信接口
 
string jsonstr = Funcs.PostFormData(new List<FormItem>() {
 
new FormItem(){Name="access_token",Value=AcessToken.GetAcessToken(),ParamType=ParamType.Text},
 
new FormItem(){Name="type",Value="image",ParamType=ParamType.Text},
 
new FormItem(){Name="media",Value=context.Server.MapPath("/images/a.jpg"),ParamType=ParamType.File}
 
}, url);
 
//3.解析返回json字符串
 
if (jsonstr.IndexOf("media_id") > -1)
 
{
 
    MediaResult result = JsonConvert.DeserializeObject<MediaResult>(jsonstr);
 
    //将获取到的media_id以及过期时间等存储到数据库中
 
    context.Response.Write("MEDIA_ID:" + result.MEDIA_ID + ",created_at:" + TimeStampUtils.GetTime(result.created_at.ToString()));
 
}
 
else
 
{
 
    ErrorResult result = JsonConvert.DeserializeObject<ErrorResult>(jsonstr);
 
    context.Response.Write("errcode:" + result.errcode + ",errmsg:" + result.errmsg);
 
}

 

注:Funcs.PostFormData方法分别传入url和参数集合(参数名、参数值、参数类型),返回响应html字符串

结果:





原文地址:https://www.cnblogs.com/notniu/p/4431128.html