Seeking assistance with understanding how to upload a file (FormData
) and an object from Angular to C# API. It seems that the HttpClient post method can only accept one body parameter, so I am unable to post both the FormData
object and the SomeObject
object simultaneously. I attempted encapsulating the SomeObject
in FormData
using FormData.append
, but without success.
Below is a snippet of the Angular frontend code:
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'
});
}
And here is a snippet of the C# API code:
[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}");
}
}