接口详情:微信公众平台新增永久素材
新增永久图文素材请求接口,POST数据就能实现,这里主要记录下C#如何通过Form表单上传文件(图片,音频,视频等)
///
/// FORM表单POST方式上传一个多媒体文件
///
/// 请求地址
/// 文件类型
/// 文件名
/// 文件流
/// 为视频文件
/// 视频文件标题
/// 视频文件描述
///
///
public static string HttpRequestPostMedia(string url, string typeName, string fileName, Stream stream,bool isVideo = false, string title = "",string introduction ="", string encoding = "UTF-8")
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = 10000;
var postStream = new MemoryStream();
#region 处理Form表单文件上传
//通过表单上传文件
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
var formdata = string.Format(formdataTemplate, typeName, fileName);
var formdataStr = postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata;//第一行换行
var formdataBytes = Encoding.ASCII.GetBytes(formdataStr);
postStream.Write(formdataBytes, 0, formdataBytes.Length);
//写入文件
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
postStream.Write(buffer, 0, bytesRead);
}
//视频文件添加请求体
if (isVideo)
{
var desStr = string.Format("{{\"title\":\"{0}\", \"introduction\":\"{1}\"}}", title, introduction);
var formdataStr2 = "\r\n--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"description\";\r\n\r\n" + desStr;
var formdataBytes2 = Encoding.ASCII.GetBytes(formdataStr2);
postStream.Write(formdataBytes2, 0, formdataBytes2.Length);
}
//结尾
var footer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(footer, 0, footer.Length);
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
#endregion
request.ContentLength = postStream != null ? postStream.Length : 0;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
#region 输入二进制流
if (postStream != null)
{
postStream.Position = 0;
//直接写入流
Stream requestStream = request.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
postStream.Close();//关闭文件访问
}
#endregion
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding)))
{
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
}
<div class="layui-card">
<div class="layui-card-header">上传图片素材</div>
<div class="layui-card-body">
<div class="layui-form-item">
<div class="layui-upload">
<div class="layui-form-item">
<label class="layui-form-label">图片备注</label>
<div class="layui-input-inline">
<input type="text" name="remark" required lay-verify="required" placeholder="请输入图片备注" autocomplete="off" class="layui-input" id="image-text-m">
</div>
<div class="layui-form-mid layui-word-aux">(图片小于2M,支持bmp/png/jpeg/jpg/gif格式)</div>
</div>
<div class="layui-upload-list">
<img class="layui-upload-img" src="~/Sources/bg-image.png" id="image-upload-m">
</div>
<button type="button" class="layui-btn" id="image-change-btn-m" style="margin-left:30px;">选择图片</button>
<button type="button" class="layui-btn" id="image-change-btn-action-m" style="margin-left:30px">开始上传</button>
</div>
</div>
</div>
</div>
upload.render({
elem: '#image-change-btn-m',
url: '', //上传地址接口
data: { 'remark': $('#image-text-m').val(), 'type': "image" },
auto: false,
bindAction: '#image-change-btn-action-m',//上传按钮
size: 2047,
accept: 'file',//限制文件大小
exts: 'bmp|png|jpeg|jpg|gif',//bmp/png/jpeg/jpg/gif //限制文件类型
choose: function (obj) {
obj.preview(function (index, file, result) {
$('#image-upload-m').attr('src', result); //展示图片
});
},
before: function (obj) {
this.data.remark = $('#image-text-m').val();
layer.msg('上传中,请稍候...', { icon: 16, time: 1000, shade: 0 });
setTimeout(function () {
}, 1000);
},
done: function (res) {
if (res.Message == "ok") {
layer.alert("素材添加成功", {
icon: 1,
shadeClose: false,
anim: 1,
btn: ['知道了']
}, function (index) {
layer.close(index);
location.reload();
});
} else {
layer.alert(res.Message, {
icon: 2,
shadeClose: false,
anim: 1,
btn: ['知道了']
});
}
},
error: function (err) {
}
});
HttpPostedFile file = HttpContext.Current.Request.Files["file"];//获取http传输的文件
var remark = HttpContext.Current.Request.Form[0].ToString();//备注
var type = HttpContext.Current.Request.Form[1].ToString();//文件类型
Stream inputStream = file.InputStream;
var data = WXMediaMethod.UploadMedia("https://api.weixin.qq.com/cgi-bin/material/add_material", accessToken, type, "media", file.FileName, inputStream); //data 为微信返回
public static string UploadMedia(string url, string accessToken, string type, string fileType, string fileName, Stream file,bool isVideo = false, string title = "",string introduction="")
{
var postUrl = string.Format(url + "?access_token={0}&type={1}", accessToken, type);
var data = HttpMethod.HttpRequestPostMedia(postUrl, fileType, fileName, file, isVideo,title,introduction);
return data;
}