最近在做關於微信公眾號接口的問題,發現上傳永久素材的地方有些小問題。
1.臨時素材和永久素材沒有關系,在微信服務器可以保存三天。新增的臨時素材只能通過media_id(臨時素材)獲取。
2.新增圖文素材以外的素材,需要使用‘新增其他類型永久素材’接口,其中文檔寫的地址為
http請求方式: POST,需使用https https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN
在測試的過程中發現,少了type屬性。我之前一直用json對象傳值進去,所以總是出現各種錯誤。
通過這個接口就可以獲得到media_id(永久素材)。
3.上傳需要使用multipart/form-data方式。
下面是代碼,在網上搜了一些高手的方法,稍微進行了一下組合,親測可用
/// <summary> /// 新增永久素材 /// </summary> /// <param name="form"></param> /// <returns></returns> [HttpPost] public string UploadLong(FormCollection form) { if (Request.Files.Count == 0) { //Request.Files.Count 文件數為0上傳不成功 return "文件數為0上傳不成功"; } var file = Request.Files[0]; if (file.ContentLength == 0) { //文件大小(以字節為單位)為0時,做一些操作 return "文件大小(以字節為單位)為0"; } else { //文件大小不為0 HttpPostedFileBase files = Request.Files[0]; string type = "image"; string url = string.Format("http://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}", token, type.ToString()); string path = "C://Users//xjh//Desktop//img//" + files.FileName; //服務器上的UpLoadFile文件夾必須有讀寫權限 files.SaveAs(path); string filename = System.Web.HttpContext.Current.Server.MapPath("/image/" + files.FileName); //返回url //var geturl = HttpUploadFile(string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}", token), file.FileName); string json = HttpUploadFile(url, filename); JObject jb = (JObject)JsonConvert.DeserializeObject(json); //todo return json; } }
以下為post方法
public static string HttpUploadFile(string url, string path) { // 設置參數 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"); int pos = path.LastIndexOf("\\"); string fileName = path.Substring(pos + 1); //請求頭部信息 StringBuilder sbHeader = new StringBuilder( string.Format( "Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] bArr = new byte[fs.Length]; fs.Read(bArr, 0, bArr.Length); fs.Close(); Stream postStream = request.GetRequestStream(); postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); postStream.Write(bArr, 0, bArr.Length); postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); postStream.Close(); //發送請求並獲取相應回應數據 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開始向目標網頁發送Post請求 Stream instream = response.GetResponseStream(); StreamReader sr = new StreamReader(instream, Encoding.UTF8); //返回結果網頁(html)代碼 string content = sr.ReadToEnd(); return content; }