












测试了n次,不能用net自带的 MultipartFormDataContent,否则微信公众号会一直报错41005错误,具体原因不详,只能拼装head字符串实现,下面是封装好的上传永久素材和临时图片素材的方法。
//上传图片 isPermanentImage=true表示永久素材 filePath为http地址,如果本地文件的自行读取
//isPermanentImage 表示是否是永久素材
private async Task<string> UploadImageAsync(string accessToken, string filePath, bool isPermanentImage) { var http = new HttpClient();//net core中改为通过IHttpClientFactory.CreateClient()实现 string url; if (isPermanentImage){
//封装图片 url = $"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={accessToken}&type=image"; } else{
//文章内容中的图片 url = $"https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={accessToken}&type=image"; } string boundary = "Upload----" + DateTime.Now.Ticks.ToString("x"); string fileName = System.IO.Path.GetFileName(filePath); var fileData = await http.GetByteArrayAsync(filePath); using var ms = new MemoryStream(); // 1. 写入 boundary byte[] boundaryBytes = Encoding.UTF8.GetBytes($"--{boundary}\r\n"); ms.Write(boundaryBytes, 0, boundaryBytes.Length); // 2. 写入媒体文件描述头 string header =$"Content-Disposition: form-data; name=\"media\"; filename=\"{fileName}\"\r\n" + $"Content-Type: {GetMime(fileName)}\r\n\r\n"; byte[] headerBytes = Encoding.UTF8.GetBytes(header); ms.Write(headerBytes, 0, headerBytes.Length); // 3. 写入文件内容 ms.Write(fileData, 0, fileData.Length); // 4. 写入结束 boundary byte[] endBytes = Encoding.UTF8.GetBytes($"\r\n--{boundary}--\r\n"); ms.Write(endBytes, 0, endBytes.Length); ms.Position = 0; // 发送请求 using HttpClient client = new HttpClient(); HttpContent content = new StreamContent(ms); content.Headers.ContentType = MediaTypeHeaderValue.Parse($"multipart/form-data; boundary={boundary}"); var response = await client.PostAsync(url, content); string json = await response.Content.ReadAsStringAsync(); Console.WriteLine(json); if (isPermanentImage) { return Newtonsoft.Json.Linq.JObject.Parse(json)["media_id"]?.ToString(); } else { return Newtonsoft.Json.Linq.JObject.Parse(json)["url"]?.ToString(); } }
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。