DEV Community

Broggi Quentin
Broggi Quentin

Posted on

How to send File from Angular To Web Api C# .Net

Passing a file from Angular to a C# Web API with .NET 5.0 can be useful when you need to upload a file to your server for processing or storage. Here's how:

1: You need to configure your C# Web API to accept uploaded files. To do this, you need to add a controller action that takes as input an object of type IFormFile. Here's what it might look like:

[HttpPost]
public async Task<IActionResult> UploadFile([FromForm] IFormFile file)
{
    byte[] fileBytes;
    using (var ms = new MemoryStream())
    {
        file.CopyTo(ms);
        fileBytes = ms.ToArray();
        // File processing

    }
}

Enter fullscreen mode Exit fullscreen mode

2: In your Angular application, you need to use the FormData object to construct an HTTP POST request containing the file to upload. You can use the append() method of FormData to add the file to the request:

uploadFile(file: File) {
    const formData = new FormData();

    formData.append('file', file, file.name);

    this.http.post('/api/upload', formData).subscribe(...);
}

Enter fullscreen mode Exit fullscreen mode

Note that in .NET 5.0 you can also use the IFormFileCollection interface to accept multiple files in a single controller action:

[HttpPost]
public async Task<IActionResult> ([FromForm] IFormFileCollection files)
{
     // File processing
}

Enter fullscreen mode Exit fullscreen mode
uploadFiles(files: FileList) {
    const formData = new FormData();

    for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i], files[i].name);
    }

    this.http.post('/api/upload', formData).subscribe(...);
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)