[英]Upload image to web API using C#
I am trying to upload an image to a web service via POST.我正在尝试通过 POST 将图像上传到 Web 服务。
The API documentation says " to upload files via POST, encoded as "multipart/form-data" and include a POST arg named "image" with the image data. Images must be of type PNG, JPG, or GIF. " API 文档说“通过 POST 上传文件,编码为“multipart/form-data”,并在图像数据中包含一个名为“image”的 POST arg。图像必须是 PNG、JPG 或 GIF 类型。
This is my code:这是我的代码:
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) { }
This code raises an exception trying to create the StringContent object.此代码在尝试创建 StringContent 对象时引发异常。
I am ok for any suggestions.我可以接受任何建议。 The API that I need to use requires Authentication, which typically is solved using a WebClient and this statement:
我需要使用的 API 需要身份验证,通常使用 WebClient 和以下语句来解决:
client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("my_API_key:"));
I am OK with using any other form of POST, like WebClient or HttpClient.我可以使用任何其他形式的 POST,例如 WebClient 或 HttpClient。
Code that finally worked, in case anyone is looking for the same answer:最终有效的代码,以防有人正在寻找相同的答案:
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 { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.