Net/Net Core微信公众号上传图片永久图片素材和内容中图片素材不能用MultipartFormDataContent的坑
【摘要】 测试了N次,不能用net自带的 MultipartFormDataContent,否则微信公众号会一直报错41005错误,具体原因不详,只能拼装head字符串实现,下面是封装好的上传永久素材和临时图片素材的方法,下面为测试好的代码,我用的是.net8,主要看head拼接部分就好,希望能帮助到大家。//上传图片 isPermanentImage=true表示永久素材 filePath为ht...
测试了N次,不能用net自带的 MultipartFormDataContent,否则微信公众号会一直报错41005错误,具体原因不详,只能拼装head字符串实现,下面是封装好的上传永久素材和临时图片素材的方法,下面为测试好的代码,我用的是.net8,主要看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();
}
}
感觉微信公众号后面会慢慢闭环了,最近几年Api权限和接口名称一直在变动,维护起来很蛋疼。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)