Since the release of ASP.NET Core 2.1 preview 1, I have been playing with it. The good news is, you can also create Angular 5 app directly from the Visual Studio 2017 without installing any third-party extensions or templates. Recently, I worked on an Angular 5 and ASP.NET Core 2.1 WEB API POC (Proof of Concept). The POC has a functionality to upload files to the server via the Angular 5 application. I thought it’s a good idea to share the solution as maybe it will save you some time. This post talks about how to upload a file from Angular 5 to ASP.NET Core 2.1 Web API.
Upload a file from Angular 5 to ASP.NET Core 2.1 Web API
First thing first, let’s create an Angular 5 app with Visual Studio 2017. To do that, open Visual Studio 2017 “Preview” version, hit Ctrl+Shift+N and select the ASP.NET Core Web Application (.NET Core) project type from the templates. When you click Ok, you will get the following prompt,
Make sure to select “ASP.NET Core 2.1” from the version dropdown and choose Angular. The Visual Studio will create an ASP.NET Core 2.1 based project with Angular 5 configured. This should create an Angular 5 app. You should run the app to make sure that there are no errors.
Create Upload API in ASP.NET Core
To support uploading on the server, add a Web API controller named
UploadController in the Controller folder. This controller has the API to upload the file and store it at a location. Add the controller with the following code.
Next, add the required HTML and component. To do that, create a new folder named “upload” inside the ClientApp->src->app directory. We need to add 2 files in this folder. First is,
upload.component.html with the following code,
Here, we are also showing the upload progress in percentage. Thanks to Angular HTTPClient events.
The second file is the Angular component to handle the upload and call the server-side web API. Add the Angular component named
upload.component.ts with the following code,
Next, we need to add the “Upload” link in the navigation bar. To do that, open the
nav-menu.component.html file located inside the nav-menu folder and add the following code just after the “Fetch Data” link.
Lastly, we need to add the newly created component to the Angular app module. We need to include the Upload component in the
app.module.ts file. After including, the
app.module.ts file should look like:
That’s it. Run the application and you should see the following.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.