DEV Community

Broggi Quentin
Broggi Quentin

Posted on

10

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

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spirits—leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay