数据发布图像和json同一时间
我试图使用C#代码在一个请求中上传图像和json,但服务器总是返回400-错误的请求。 使用fiddler执行相同的请求将返回状态码200. help ...
这是我的提琴手代码:
------ WebKitFormBoundary7MA4YWxkTrZu0gW内容处理:form-data; name =“application / json”Content-Type:application / json
{ “类型”: “个人”, “注释”:[ “的Lorem”, “存有”]} ------ WebKitFormBoundary7MA4YWxkTrZu0gW--内容处置:形状数据; NAME = “fieldNameHere”; 文件名= “1111.jpg”
内容类型:image / jpeg
<@INCLUDE C: Users user Desktop New folder 1111.jpg @>
并在C#中实现:
var boundary = "Upload----" + DateTime.Now.Ticks.ToString();
MultipartFormDataContent form = new MultipartFormDataContent(boundary);
StringContent content = new StringContent(bodyJson);
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
form.Add(content, "application/json");
var imageContent = new ByteArrayContent(image);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
form.Add(imageContent, "image/jpeg", "image.jpg");
var responseTask = _httpClient.PostAsync(url, form).Result;
答复总是一样的:
您可以将参数作为字符串内容传递,请检查下面的示例。
public async Task<JObject> ExecutePostAsync(Stream myStreem, string url, string token, string parameter1, string parameter2, string parameter3)
{
try
{
using (var content = new MultipartFormDataContent("----MyBoundary"))
{
using (var memoryStream = myStreem)
{
using (var stream = new StreamContent(memoryStream))
{
content.Add(stream, "file", Guid.NewGuid().ToString() + ".jpg");
content.Add(new StringContent(parameter1), "parameter1");
content.Add(new StringContent(parameter3), "parameter2");
content.Add(new StringContent(parameter3), "parameter3");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var responce = await client.PostAsync(url, content);
string contents = await responce.Content.ReadAsStringAsync();
return (JObject.Parse(contents));
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
在API中从FORM请求中获取数据
public async Task<IHttpActionResult> UploadFile()
{
string parameter1 = HttpContext.Current.Request.Form["parameter1"];
string parameter2 = HttpContext.Current.Request.Form["parameter2"];
string parameter3 = HttpContext.Current.Request.Form["parameter3"];
}
链接地址: http://www.djcxy.com/p/75405.html