我有以下MVC帖子。 它将文件内容发布到API。
[HttpPost]
public ActionResult FileUpload_Post()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
using (HttpClient client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
byte[] fileBytes = new byte[file.InputStream.Length + 1]; file.InputStream.Read(fileBytes, 0, fileBytes.Length);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
content.Add(fileContent);
var result = client.PostAsync(requestUri, content).Result;
if (result.StatusCode == System.Net.HttpStatusCode.Created)
{
ViewBag.Message= "Created";
}
else
{
ViewBag.Message= "Failed";
}
}
}
}
return View();
}
如果我想传递其他自定义对象(最好是json格式)以及文件内容怎么办?
CustomObject obj = new CustomObject;
obj.FirstName = "A";
object.LastName = "B";
注意:以下是接收上述请求的Api方法。
[HttpPost]
public HttpResponseMessage Upload()
{
if(!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
if (System.Web.HttpContext.Current.Request.Files.Count > 0)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
....
// save the file
....
return new HttpResponseMessage(HttpStatusCode.Created);
}
else
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
答案 0 :(得分:0)
首先,您需要将CustomObject
序列化为json。例如使用Json.NET
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
然后您可以将jsonString
添加到MultipartFormDataContent
,例如:
var jsonContent = new StringContent(jsonString);
content.Add(jsonContent, "CustomObject");
在Upload
API方法中,按
var jsonString = System.Web.HttpContext.Current.Request.Form["CustomObject"];
如果API项目引用了类CustomObject
,您可以使用以下代码反序列化jsonString
:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomObject>(jsonString);
如果没有,您也可以将其反序列化为dynamic
对象:
var obj = Newtonsoft.Json.Linq.JObject.Parse(jsonString);