Net/Net Core微信公众号上传图片永久图片素材和内容中图片素材不能用MultipartFormDataContent的坑
测试了N次不能用net自带的 MultipartFormDataContent否则微信公众号会一直报错41005错误具体原因不详只能拼装head字符串实现下面是封装好的上传永久素材和临时图片素材的方法下面为测试好的代码我用的是.net8主要看head拼接部分就好希望能帮助到大家。//上传图片 isPermanentImagetrue表示永久素材 filePath为http地址如果本地文件的自行读取 //isPermanentImage 表示是否是永久素材 private async Taskstring 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}typeimage; } else{ //文章内容中的图片 url $https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token{accessToken}typeimage; } 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(); } }感觉微信公众号后面会慢慢闭环了最近几年Api权限和接口名称一直在变动维护起来很蛋疼。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2477886.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!