C# 使用C将图像上载到web API#
我正在尝试通过POST将图像上传到web服务 API文档说明“通过POST上传文件,编码为“多部分/表单数据”,并在图像数据中包含名为“image”的POST参数。图像必须为PNG、JPG或GIF类型。” 这是我的代码:C# 使用C将图像上载到web API#,c#,web-services,api,http-post,image-uploading,C#,Web Services,Api,Http Post,Image Uploading,我正在尝试通过POST将图像上传到web服务 API文档说明“通过POST上传文件,编码为“多部分/表单数据”,并在图像数据中包含名为“image”的POST参数。图像必须为PNG、JPG或GIF类型。” 这是我的代码: Bitmap myImage = new Bitmap("myImage.jpg"); byte[] myFileData = (byte[])(new ImageConverter()).ConvertTo(myImage, typeof(byte[])); strin
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 { }
}
您实际上不需要将图像加载到位图实例中(至少在不需要客户端图像转换的情况下)。对我来说,直接通过WebClient.UploadFile上传图像效果很好。不幸的是,我需要使用的API明确指出不要这样做,相反,它必须编码为“多部分/表单数据”,并包含一个名为“image”的POST-arg。