C#:从正文和文件中将模型发布为MultipartFormDataContent

时间:2018-09-06 18:03:23

标签: c# asp.net-core multipartform-data

我正在寻找一种在一个请求中发送模型和图像的方法。我试图从身体发送模型,但是我不知道如何发送文件。除了在其他文件中发送图像和模型之外,还有其他方法吗?

这是我的API中的POST方法:

[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();
}

这是我的应用程序中的代码:

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);
    }
}

1 个答案:

答案 0 :(得分:1)

要通过File参数传递Model,您需要将数据作为表单数据发布。

请按照以下步骤操作:

  1. FromBody更改为FromForm

        [HttpPost]
    [Route("UploadNewEvent")]
    public async Task<IActionResult> CreateNewEventAsync([FromForm] EventModel model)
    {
        // do sth with model later    
        return Ok();
    }
    
  2. 更改客户端代码以发送表单数据而不是json字符串

        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;
    
  3. EventModel

    public class EventModel
    {
    public int Id { get; set; }
    public string Name { get; set; }
    public IFormFile File { get; set; }
    }