1 public string UploadImgByB64(string b64) 2 { 3 //access_token 需要自己获取 4 string access_token = getToken(); 5 string url = $"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=image"; 6 byte[] data = Convert.FromBase64String(b64); 7 var boundary = "fbce142e-4e8e-4bf3-826d-cc3cf506cccc"; 8 var client = new HttpClient(); 9 client.DefaultRequestHeaders.Add("User-Agent", "KnowledgeCenter"); 10 client.DefaultRequestHeaders.Remove("Expect"); 11 client.DefaultRequestHeaders.Remove("Connection"); 12 client.DefaultRequestHeaders.ExpectContinue = false; 13 client.DefaultRequestHeaders.ConnectionClose = true; 14 var content = new MultipartFormDataContent(boundary); 15 content.Headers.Remove("Content-Type"); 16 content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary); 17 var contentByte = new ByteArrayContent(data); 18 content.Add(contentByte); 19 contentByte.Headers.Remove("Content-Disposition"); 20 contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name="media";filename="{Guid.NewGuid()}.png"" + ""); 21 contentByte.Headers.Remove("Content-Type"); 22 contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/png"); 23 try 24 { 25 var result2 = client.PostAsync(url, content); 26 if (result2.Result.StatusCode != HttpStatusCode.OK) 27 throw new Exception(result2.Result.Content.ReadAsStringAsync().Result); 28 string jsonstr = result2.Result.Content.ReadAsStringAsync().Result; 29 var dic = Newtonsoft.Json.Linq.JObject.Parse(jsonstr); 30 return dic["media_id"].ToString(); 31 } 32 catch (Exception ex) 33 { 34 return null; 35 } 36 }