接口文档地址:
问题描述:
在C#代码以form-data方式上传素材后,一直报错,分别是:
media data missing和invalid file type两类错误
rid:66977e52-389697cb-26116c5d
尝试过的方法:
1、确保官方接口参数正确可调用:
使用postman工具进行接口调用,返回结果正常
2、确保编写的C#代码正确可执行:
同样的代码,调用本地服务器接口,文件上传正常并可以读取
3、求助问题与代码:
是否为异平台(.Net平台与微信所采用的技术平台)之间的兼容性问题,已经摸索良久,希望有前辈给予指导
上传过程的函数体代码为(注释部分代码为一些卑微的排除性尝试,目前这是稳定获得以上两个错误返回的最小场景代码):
private string UploadMedia(string url, string fileType, string fileName, byte[] fileData)
{
using (HttpClient httpClient = new HttpClient())
{
using (var form = new MultipartFormDataContent())
{
using (MemoryStream stream = new MemoryStream(fileData))
{
string filePath = @"E:\Temp\112211.jpg";
StreamContent fileContent = new StreamContent(System.IO.File.OpenRead(filePath));
fileName = System.IO.Path.GetFileName(filePath);
form.Add(fileContent, "media", fileName);
//fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
//StreamContent fileContent = new StreamContent(stream, fileData.Length);
//fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
//form.Add(fileContent, "media", fileName);
NameValueHeaderValue boundaryValue = form.Headers.ContentType.Parameters.Single(p => p.Name == "boundary");
boundaryValue.Value = boundaryValue.Value.Replace("\"", string.Empty);
//switch (fileType)
//{
// case "image":
// fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
// break;
// case "voice":
// fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("audio/amr");
// break;
// case "video":
// fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("video/mp4");
// break;
// case "thumb":
// fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
// break;
// default:
// throw new ArgumentException("Invalid file type");
//}
HttpResponseMessage response = httpClient.PostAsync(url, form).Result;
//response.EnsureSuccessStatusCode();
string content = response.Content.ReadAsStringAsync().Result;
return content;
}
}
}
}
求助下大模型还快一些
你这里应该是没有设置formdata的类型:application/octet-stream
public class WeChatApiClient
{
private readonly string accessToken;
private readonly HttpClient client;
public WeChatApiClient(string accessToken)
{
this.accessToken = accessToken;
this.client = new HttpClient();
}
public async Task<string> UploadMediaToCodeAuditAsync(string filePath, string mediaType)
{
var formData = new MultipartFormDataContent();
// 假设API要求文件字段名为"media"
var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType); // 设置文件MIME类型,如"application/octet-stream"
formData.Add(fileContent, "media", Path.GetFileName(filePath));
现在我们换了个方案,使用其他方法进行调用,问题暂时解决了
帖子为啥在交流区里不显示?