使用 C# 将图像上传到网络 API

Upload image to web API using C#

我正在尝试通过 POST 将图像上传到 Web 服务。

API 文档说“通过 POST 上传文件,编码为 "multipart/form-data" 并包含一个名为 [=28= 的 POST arg ] 与图像数据。图像必须是 PNG、JPG 或 GIF 类型。"

这是我的代码:

Bitmap    myImage = new Bitmap("myImage.jpg");
byte[] myFileData = (byte[])(new ImageConverter()).ConvertTo(myImage, typeof(byte[]));
string myBoundary = "------------------------" + DateTime.Now.Ticks;
var       newLine = Environment.NewLine;
string myContent = 
  "--" + myBoundary + newLine + 
  "content-disposition: form-data; name=\"image\"; filename=\"myImage.jpg\"" + newLine + 
  "Content-Type: image/jpeg" + newLine +
  "Content-Transfer-Encoding: binary" + newLine +
  newLine +
  Encoding.Default.GetString(myFileData) + newLine + 
  "--" + myBoundary + "--";

try {
    using (var httpClient = new HttpClient()) 
    using (var content = new StringContent(myContent, Encoding.Default, "multipart/form-data, boundary=" + myBoundary)) 
    using (var response = await httpClient.PostAsync("http://my_API_URL", content)) {
        string responseData = await response.Content.ReadAsStringAsync();
    }
}
catch (Exception myExp) { }

此代码在尝试创建 StringContent 对象时引发异常。

我愿意提出任何建议。我需要使用的 API 需要身份验证,这通常使用 WebClient 和此语句解决:

client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("my_API_key:"));

我可以使用任何其他形式的 POST,例如 WebClient 或 HttpClient。

最终有效的代码,以防有人在寻找相同的答案:

Bitmap    myImage = new Bitmap("myImage.jpg");
byte[] myFileData = (byte[])(new ImageConverter()).ConvertTo(myImage, typeof(byte[]));
string myBoundary = "---------------------------7df3c13714f0ffc";
var       newLine = Environment.NewLine;
string  myContent =
  "--" + myBoundary + newLine + 
  "Content-Disposition: form-data; name=\"image\"; filename=\"myImage.jpg\"" + newLine +
  "Content-Type: image/jpeg" + newLine +
  newLine +
  Encoding.Default.GetString(myFileData) + newLine +
  "--" + myBoundary + "--";

using (var client = new WebClient()) {
    try {
        client.Headers["Authorization"] = "Basic xxxxxx";
        client.Headers["Content-Type"]  = "multipart/form-data; boundary=" + myBoundary;
        client.UploadString(new Uri(myURL), "POST", myContent);
        totalAPICalls++;
    }
    catch { }
}