C#:从正文和文件中将模型发布为MultipartFormDataContent [英] C#: Posting Model from body and file as MultipartFormDataContent
本文介绍了C#:从正文和文件中将模型发布为MultipartFormDataContent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种在一个请求中发送模型和图像的方法.我试图从身体发送模型,但是我不知道如何发送文件.除了在其他文件中发送图像和模型之外,还有其他方法吗?
I'm looking for a way to send model and image in one request. I tried to send my model from body, but I don't know how to send the file. Is there another way than sending image and model in a different files?
这是我的API中的POST方法:
Here's the POST method from my API:
[HttpPost]
[Route("UploadNewEvent")]
public async Task<IActionResult> CreateNewEventAsync([FromBody] EventModel model)
{
var file = this.Request.Form.Files.LastOrDefault();
if (file != null)
{
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
using (var fileStream = new FileStream(Path.Combine(uploads, "test.jpg"), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
// do sth with model later
return Ok();
}
这是我的应用程序中的代码:
And here's the code from my App:
public async Task SendNewEvent(EventModel model, MediaFile photo)
{
var uri = $"{baseUri}api/User/Event/CreateNewEvent";
if (photo != null)
{
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StreamContent(photo.GetStream()), "\"file\"", $"\"{photo.Path}\"");
var httpClient = new HttpClient();
var jsonObject = JsonConvert.SerializeObject(model);
var stringContent = new StringContent(jsonObject, Encoding.UTF8, "application/json");
var httpResponseMessage = await httpClient.PostAsync(uri, stringContent);
}
}
推荐答案
要通过File参数传递Model,您需要将数据作为表单数据发布.
For passing Model with File parameter, you need to post data as form-data.
请按照以下步骤操作:
-
将
FromBody
更改为FromForm
[HttpPost]
[Route("UploadNewEvent")]
public async Task<IActionResult> CreateNewEventAsync([FromForm] EventModel model)
{
// do sth with model later
return Ok();
}
更改客户端代码以发送表单数据而不是json字符串
Change client code to send form-data instead of json string
var uri = $"https://localhost:44339/UploadNewEvent";
FileStream fileStream = new FileStream(@"filepath\T1.PNG", FileMode.Open);
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StreamContent(fileStream), "\"file\"", @"filepath\T1.PNG");
// EventModel other fields
multipartContent.Add(new StringContent("2"), "Id");
multipartContent.Add(new StringContent("Tom"), "Name");
var httpClient = new HttpClient();
var httpResponseMessage = httpClient.PostAsync(uri, multipartContent).Result;
EventModel
EventModel
public class EventModel
{
public int Id { get; set; }
public string Name { get; set; }
public IFormFile File { get; set; }
}
这篇关于C#:从正文和文件中将模型发布为MultipartFormDataContent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文