@using (Html.BeginForm("UploadVideo", "AddForeverVideo", FormMethod.Post, new { enctype = "multipart/form-data" })) {
选择上传媒体文件:
}
上面是一个input type为file ,name=“description” id=“description”还有一个submit提交按钮
---------------------------------
上面是前台页面
-------------------------------------------------------------
///
/// 这个借口没有通过
///
///
///
public ActionResult UploadVideo(FormCollection collection)
{
string result = "";
HttpPostedFileBase file = Request.Files[0];
string access_token = pub.GetExistAccessToken();
string localpath = "D:\Simple\MyTest\image\" + file.FileName;
file.SaveAs(localpath);//保存本地用于数据库
result = WXApi.AddForeverVideo(access_token, file, "video");
return Content(result);
}
------------------
上面是控制器代码
------------------------------
public static string MaterialUploads(string accessToken, HttpPostedFileBase isFile, string materialType, string title = "", string introduction = "")
{
string url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}";
url = string.Format(url, accessToken, materialType);
//设置提交表单的名称
string formName = materialType == "video" ? "description" : "media";
byte[] datas = null;
#region 组合正文
//换行
string CRLF = "\r\n";
//边界标识
string Identification = "----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
try
{
//生成表单信息
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(Identification);
sb.Append(CRLF);
sb.Append("Content-Disposition: form-data; id=\"" + formName + "\"; name=\"" + formName + "\"; filename=\"" + isFile.FileName + "\"");
sb.Append(CRLF);
sb.Append("Content-Type: " + isFile.ContentType.ToLower() + "");
sb.Append(CRLF);
sb.Append(CRLF);
//如果是视频数据,就添加视频标题与视频的描述信息
if (materialType.ToLower() == "video")
{
sb.Append(" description=\"{\"title\":\"" + title + "\", \"introduction\":\"" + introduction + "\"}\"");
sb.Append(CRLF);
sb.Append(CRLF);
}
//头部与尾部
string header = sb.ToString();
string foot = CRLF + "--" + Identification + "--" + CRLF;
//转为byte[]流
byte[] headerbytes = Encoding.UTF8.GetBytes(header);
byte[] footbytes = Encoding.UTF8.GetBytes(foot);
List<byte> datalist = new List<byte>();
//转换为btye[]数据流
Stream stream = isFile.InputStream;
byte[] data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
datalist.AddRange(headerbytes);
datalist.AddRange(data);
datalist.AddRange(footbytes);
//组合完整的流数据
datas = datalist.ToArray<byte>();
}
catch (Exception)
{
return "正文组合失败";
}
#endregion
return MaterialUploadd(datas, url, Identification);
}