使用C#将图像上传到Web API

时间:2015-08-30 08:11:11

标签: c# web-services api http-post image-uploading

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

API文档说“通过POST上传文件,编码为”multipart / form-data“并包含一个名为”image“的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。

1 个答案:

答案 0 :(得分:0)

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

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 { }
}