1. 程式人生 > 實用技巧 >企業微信上傳臨時素材

企業微信上傳臨時素材

 1 public static QiyeMaterialMsg UploadQyImg(string path)
 2         {
 3             try
 4             {
 5                 HttpWebRequest request = WebRequest.Create($"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={Config.access_token}&type=image") as HttpWebRequest;
 6 
 7                 if
(request != null) 8 { 9 CookieContainer cookieContainer = new CookieContainer(); 10 request.CookieContainer = cookieContainer; 11 request.AllowAutoRedirect = true; 12 request.Method = "POST"; 13 string
boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線 14 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; 15 byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); 16 byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("
\r\n--" + boundary + "--\r\n"); 17 18 int pos = path.LastIndexOf("\\"); 19 string fileName = path.Substring(pos + 1); 20 21 //請求頭部資訊 22 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); 23 byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); 24 25 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); 26 byte[] bArr = new byte[fs.Length]; 27 fs.Read(bArr, 0, bArr.Length); 28 fs.Close(); 29 30 Stream postStream = request.GetRequestStream(); 31 postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); 32 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); 33 postStream.Write(bArr, 0, bArr.Length); 34 postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); 35 postStream.Close(); 36 37 //傳送請求並獲取相應迴應資料 38 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 39 //直到request.GetResponse()程式才開始向目標網頁傳送Post請求 40 Stream instream = response.GetResponseStream(); 41 StreamReader sr = new StreamReader(instream, Encoding.UTF8); 42 string content = sr.ReadToEnd(); 43 return JsonHelper.JsonDeserialize<QiyeMaterialMsg>(content); 44 } 45 46 return new QiyeMaterialMsg(); 47 } 48 catch (Exception e) 49 { 50 LogHelper.ErrorLog(e.Message); 51 return new QiyeMaterialMsg { errmsg = e.Message }; 52 } 53 }