Upload file in Angular 2

In this tutorial we will discuss how to upload file in Angular 2.

Here is the view of uploading file. There is an option to browse the file as you select the file fileChange function will be called which is written in FileComponent.


Create a component :

html :                                                                                                                                     

In this component I have written fileChange function which calls the service to upload the file. But before calling the function we create the FormData object and then append the file object into FormData object.

component.ts


Here we have written the service to call the api.

service.ts

While sending the file we also need to define headers. So here in header.ts I have written 2 functions, 1st is head() which used while sending any JSON request and 2nd is formHead() which is used while sending form data.
So here because we are sending form data that’s why I will use formHead() function.

Instead of writing headers manually you also can use Angular 2 Intercepters here.

headers.ts

Share This:

One thought on “Upload file in Angular 2

Leave a Reply

Your email address will not be published. Required fields are marked *