How to upload images in Angular?

In these article i discuss on How to upload images in our angular Application.
For that first we need to install module called “angular2-image-upload” using below command.
“npm install angular2-image-upload”
Now in app.module.ts file


import { ImageUploadModule } from 'angular2-image-upload';

@NgModule({
.....
imports:[
......
ImageUploadModule.forRoot(),
......
]

....

})

In app.module.ts file first we need to import above code.
Then you can use in the component template file easily like below.


<image-upload
[url]="imgeposturl"
[max]="10000"
[headers]="myHeaders"
[buttonCaption]="'ADD IMAGE'"
[dropBoxMessage]="'Drop Image'"
[extensions]="['jpg','png','gif','jpeg']"
(onFileUploadFinish)="onUploadFinished($event)">
</image-upload>

when we write above code in it will looks like



In above example we have passed some option for the uploading images.
1) URL: where we want to uploaded image to post.
2) Max: how many files upload.
3) Header: For passing authentication token. Images post from our server or not.
4) buttonCaption: We can change name of the button.
5) dropBoxMessage: We can change drop message.
6) extensions: Which extension we need to allow for uploading.
Also refer for more optionĀ  from “angular2-image-upload

Pass one Event function called “onFileUploadFinish” When upload images completed it will trigger.
In our component file looks like below code.


............
public imgeposturl: string;
public myHeaders: any;
constructor(){

 this.imgeposturl = "http://exmple.com" // URL where you want to handle uploaded image.
 this.myHeaders = [
            { header: 'Accesstoken', value: 'Token To validate on server.' }
        ];


}

 onUploadFinished(file: any) {

//after uploading image it will return on this function we can get value from server.

}

............

From these way we can upload images using Angular very easily.

Spread the love
  • 19
  •  
  •  
  •  
  •  
  •  
  •  
  •