Angular 前端/C# API 后端 - 发布表单数据(文件)和对象

问题描述 投票:0回答:1

希望有人可以帮助我理解从 Angular 到 C# API 上传文件 (

FormData
) 和对象的过程。 据我了解,HttpClient post 方法仅接受一个主体参数,因此我可以发布
FormData
对象或
SomeObject
对象,但不能同时发布两者。 我尝试将
SomeObject
封装在
FormData
中(使用
FormData.append
),但没有成功。

Angular 前端代码片段:

uploadAttachment(abcId: number, someObject: SomeObject)
{
  const url = this.apiUrl + '/abc/' + abcId;

  const formData = new FormData();
  formData.append('file', fileData);

  return this.http.post<ScopeItemAttachment>(url, formData, 
  {
    reportProgress: true,
    observe: 'events'
  });
}

C# API 片段:

[HttpPost("{abcID}", Name = "UploadAttachment")]
public IActionResult UploadAttachment(int abcId, SomeObject someObject)
{
    try
    {
        var file = Request.Form.Files[0];
        var temp = Request.Form.Keys;

        if (file.Length > 0)
        {
            fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

            MemoryStream ms = new MemoryStream();
            file.CopyTo(ms);

            ms.Close();
            ms.Dispose();

            return Ok();
        }
        else
            return BadRequest(new { message = "File content length must be greater than zero" });
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"Internal server error: {ex}");
    }
}
c# angular typescript form-data angular-httpclient
1个回答
1
投票

假设您的

SomeObject
实现如下:

public class SomeObject
{
    public IFormFile File { get; set; }
}
  1. [FromForm]
    属性应用于请求正文 (
    someObject
    )。

  2. 您可以通过

    file
    而不是
    someObject.File
    获得
    Request.Form.File[0]

[HttpPost("{abcId}", Name = "UploadAttachment")]
public IActionResult UploadAttachment(int abcId, [FromForm] SomeObject someObject)
{

    var file = someObject.File;

    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.