使用C#代码,微信公众号推送图片 报错为”errmsg”:”mediadata missing hint:
我的代码是这样写的(https://i.stack.imgur.com/mU6At.jpg)
public async Task UploadMediaAsync(string accessToken, string filePath, string mediaType)
{
Debug.WriteLine($”Preparing to upload file. Access token: {accessToken}, File path: {filePath}, Media type: {mediaType}”);
if (!File.Exists(filePath))
{
throw new FileNotFoundException("File not found.", filePath);
}
var fileInfo = new FileInfo(filePath);
var fileName = fileInfo.Name;
var contentType = MimeMappingHelper.GetMimeMapping(fileName);
var fileLength = fileInfo.Length;
string uploadUrl = $"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={accessToken}&type={mediaType}";
using (var fileStream = File.OpenRead(filePath))
{
var fileContent = new StreamContent(fileStream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = ""media"",
FileName = $""{fileName}""
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
var formData = new MultipartFormDataContent
{
{ fileContent, "media", fileName }
};
Debug.WriteLine("Sending the request to upload file...");
var response = await _httpClient.PostAsync(uploadUrl, formData);
var responseContent = await response.Content.ReadAsStringAsync();
Debug.WriteLine($"Upload response: {responseContent}");
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Request failed with status code: {response.StatusCode}, Content: {responseContent}");
}
var uploadData = JsonConvert.DeserializeObject<dynamic>(responseContent);
if (uploadData.errcode != null)
{
throw new Exception($"Error in upload response: {responseContent}");
}
Debug.WriteLine($"Media ID: {uploadData.media_id}");
return uploadData.media_id;
}
}
New contributor