使用c#上传图像到web API

本文关键字:web API 图像 使用 | 更新日期: 2023-09-27 18:10:20

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

API文档说"通过POST上传文件,编码为"multipart/form-data",并包含一个名为"image"的POST参数与图像数据。图像必须为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。

使用c#上传图像到web API

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

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