如何用C#通过Meta WhatsApp API正确上传图片?
问题:C#调用WhatsApp API上传图片失败(curl命令正常)
在Visual Studio项目中尝试通过WhatsApp API上传图片,以下curl命令在Windows 7终端/cmd可正常运行:
curl --insecure POST "https://graph.facebook.com/v18.0/********/media" ^ -H "Authorization: Bearer ********" ^ -F "file=@\"C:/dune2.jpg\"" ^ -F "type=\"image/jpeg\"" ^ -F "messaging_product=\"whatsapp\""
已用C#成功发送文本消息和带HTTP链接的文件,但上传图片时请求出现问题,C#代码如下:
string token = "*********"; string idTelefono = "*********"; HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://graph.facebook.com/v18.0/" + idTelefono + "/media"); request.Headers.Add("Authorization", "Bearer " + token); MultipartFormDataContent content = new MultipartFormDataContent(); content.Add(new ByteArrayContent(File.ReadAllBytes("D:\\Windows Libraries\\Desktop\\dune2.jpg")), "file",Path.GetFileName("D:\\Windows Libraries\\Desktop\\dune2.jpg")); content.Add(new StringContent("image/jpeg"), "type"); content.Add(new StringContent("whatsapp"), "messaging_product"); request.Content = content; HttpResponseMessage response = await client.SendAsync(request); string responseBody = await response.Content.ReadAsStringAsync(); MessageBox.Show(responseBody);
收到错误:
"(#100) Param files must be a file with one of the following types: (HERE GOES A LONG LIST OF FORMAT/TYPES)... Received file of type ".", "type":"OAuthException","code":100...
是否需要对文件进行不同编码,或在内容中添加额外的type参数?
注:添加全局Content-type头会导致请求异常,因此并非头部相关问题。
解决方案
错误提示显示API识别到的文件类型是".",核心原因是文件内容未指定正确的MIME类型。虽然全局添加Content-Type头会报错,但单个文件的ByteArrayContent需要单独设置Content-Type,让API能识别文件类型。
修改C#代码中添加文件内容的部分:
// 读取文件字节并创建内容 byte[] fileBytes = File.ReadAllBytes("D:\\Windows Libraries\\Desktop\\dune2.jpg"); var fileContent = new ByteArrayContent(fileBytes); // 为文件内容设置正确的MIME类型 fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); MultipartFormDataContent content = new MultipartFormDataContent(); // 添加带MIME类型的文件内容 content.Add(fileContent, "file", Path.GetFileName("D:\\Windows Libraries\\Desktop\\dune2.jpg")); content.Add(new StringContent("image/jpeg"), "type"); content.Add(new StringContent("whatsapp"), "messaging_product");
说明
- 为
ByteArrayContent单独设置Content-Type后,API就能正确识别图片的MIME类型,不会再返回"Received file of type ."的错误。 - 确保
Path.GetFileName获取到的文件名包含.jpg后缀,避免API无法通过后缀推断类型。
内容的提问来源于stack exchange,提问作者albertzen
相关产品推荐
相关产品推荐

