希望有人可以帮助我理解从 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}");
}
}
假设您的
SomeObject
实现如下:
public class SomeObject
{
public IFormFile File { get; set; }
}
将
[FromForm]
属性应用于请求正文 (someObject
)。
您可以通过
file
而不是 someObject.File
获得 Request.Form.File[0]
。
[HttpPost("{abcId}", Name = "UploadAttachment")]
public IActionResult UploadAttachment(int abcId, [FromForm] SomeObject someObject)
{
var file = someObject.File;
...
}