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

xienkqul  于 2022-11-15  发布在  C#
关注(0)|答案(1)|浏览(184)

我正在尝试通过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。

3z6pesqy

3z6pesqy1#

如果有人在寻找同样的答案,那么代码最终会起作用:

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

相关问题