话不多说直接上源码
请求实体
public class AddVideoRequest { /// <summary> /// 文件流 /// </summary> public System.IO.Stream stream { get; set; }
/// <summary> /// 文件名称 /// </summary>
public string name { get; set; }
/// <summary> /// 文件全称,带后缀 /// </summary> public string file_name { get; set; } /// <summary> /// 字节长度 /// </summary> public long length { get; set; }
/// <summary> /// 视频标题 /// </summary> public string title { get; set; }
/// <summary> /// 视频描述 /// </summary> public string describe { get; set; } }
上传方法 public async Task<ResponseModel<AddMediaResponse>> AddVideo(AddVideoRequest video_request, string access_token)
{
try
{
string url = $"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=video";
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("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
//请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", video_request.file_name));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
Stream fs = video_request.stream;
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();
Stream postStream = await request.GetRequestStreamAsync();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
postStream.Write(Encoding.UTF8.GetBytes("--" + boundary + "\r\n"));
postStream.Write(Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"description\";\r\n\r\n"));
postStream.Write(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { title = video_request.title, introduction = video_request.describe })));
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
string content = sr.ReadToEnd();
var res = JsonConvert.DeserializeObject<AddMediaResponse>(content);
return new ResponseModel<AddMediaResponse>
{
success = res.errcode == 0,
data = res,
error_message = res.errmsg,
body = content
};
}
catch (Exception ex)
{
return new ResponseModel<AddMediaResponse> { success = false, error_message = ex.Message };
}
}
|
请发表评论