string access_token = responseModel.Token;
string url = $"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image";
using (var form = new MultipartFormDataContent())
{
// 读取图片文件
byte[] imageData = System.IO.File.ReadAllBytes(App.WebHostEnvironment.WebRootPath+"/"+ testpath);
ByteArrayContent imageContent = new ByteArrayContent(imageData);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpg");
// 添加图片内容到表单
form.Add(imageContent,"media","test.jpg");
// 发送POST请求
HttpResponseMessage response = await _httpClient.PostAsync(url, form);
// 处理响应
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// 解析响应获取返回的media_id等信息
// 在此仅是简单示例,可根据实际返回内容进行解析
return responseBody;
}
else
{
return "上传失败,HTTP状态码: " + response.StatusCode;
}
}
{"errcode":41005,"errmsg":"media data missing hint: [DXHR603679020] rid: 65d1b1d7-3586cc15-0507be27"}
请求帮助
参考这个https://blog.csdn.net/wu1020300665/article/details/127735924
string access_token = responseModel.Token;
string url = $"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image";
string path = App.WebHostEnvironment.WebRootPath + "/" + testpath;
byte[] imageData = System.IO.File.ReadAllBytes(path);
var boundary = DateTime.Now.Ticks.ToString("X");
_httpClient.DefaultRequestHeaders.Remove("Expect");
_httpClient.DefaultRequestHeaders.Remove("Connection");
using (var content = new MultipartFormDataContent())
{
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
using (var contentByte = new ByteArrayContent(imageData))
{
content.Add(contentByte);
contentByte.Headers.Remove("Content-Disposition");
contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"test.jpg\"" + "");
contentByte.Headers.Remove("Content-Type");
contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/jpg");
try
{
return await _httpClient.PostAsync(url, content).Result.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
return ex.Message;
}
}
}