Uploading files from Angular 2 and ASP.NET Core Web API – Part 2
This is the part 2 demonstrating how to save the files sent by Angular 2 on ASP.NET Core server. Please check out part 1 for Angular 2.
I have amended the code slightly while adding to to this blog post but basics remain the same.
[HttpPost("Upload")]
public async Task<IActionResult> Upload()
{
var attachmentId= Request.Form["attachmentId"];
await SaveFilesAndUpdateDatabase(attachmentId);
var output = Mapper.Map<DetailsViewModel>(entity);
return CreatedAtRoute("GetAttachment", new { controller = "Attachments", id = attachmentId}, output);
}
private async Task SaveFilesAndUpdateDatabase(int attachmentId)
{
var files = Request.Form.Files;
foreach (var file in files)
{
if (file.Length > 0)
{
var uniqueName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
var savePath = Path.Combine(_uploadPath, uniqueName);
using (var fileStream = new FileStream(savePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
// saving to database logic ca go here
}
}
}
}
Please check out part 1 for Angular 2.
