March 04, 2021 by Anuraj Estimated read time : 8 mins
This article discuss about uploading files from an Angular application to ASP.NET Core backend. First you need to create an ASP.NET Core Angular project. Once it is done, you need to create an angular component. And then you can modify the backend implementation.
Creating an Angular component
To create an angular component, you need to run the following command - ng generate component fileupload --skip-import --skip-tests -s. Next you need to modify the typescript file - fileupload.component.ts like this.
In the above code, when a user browse files, the on change event will be fired. And then upload the file with httpclient using FormData object. And in the fileupload.component.html you need to modify and include HTML like this.
In the next section you will learn how to read and save in ASP.NET Core.
Implementing the backend
In ASP.NET Core you can create a controller, and create an action method. In the action method, you can use Request.Form.Files to read the uploaded files with Form Data from Angular client.
The above code is using the Request.Form.Files options. You can also use the Request.ReadFormAsync() method which helps you to read the files asynchronously, here is the code for reading the file asynchronously with the help of Request.ReadFormAsync() method.
ASP.NET Core also supports File Upload with the help of form binding. Here is the implementation in the ASP.NET Core controller.
And here is the Profile class.
And from Angular client you can use the Angular forms. Here is the Angular code which upload and submit the data to server.
And there is one specific code block which helps to populate the File value to Angular form control. Here is the code, which triggered on the change event of File Upload control.
And here is the HTML code for the Form
Here is the screenshot of the application running.
This way you can implement File Upload from Angular to ASP.NET Core and how to store them in Azure Blob storage. You can use the model binding implementation if you are planning to use upload a file along with other form fields like name or email.