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 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<h2>Upload Files Sample</h2>
{{fileUploadMsg}}
<div class="fileUpload btn btn-primary" *ngIf="isUploadBtn">
<span>Upload</span>
<input type="file" id="btnUpload" value="Upload" (change)="fileChange($event)" class="upload" />
</div>
<style>
.fileUpload {
position: relative;
overflow: hidden;
margin: 20px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
</style>
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { FileService } from '../_services/index';
@Component({
selector: 'app-file',
templateUrl: './file.component.html',
styleUrls: ['./file.component.css']
})
export class FileComponent implements OnInit {
private isUploadBtn: boolean = true;
private fileUploadMsg: string;
constructor(private fileService: FileService) {
}
//file upload event
fileChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
this.fileService.postFile(formData)
.subscribe(data => {
this.fileUploadMsg = data.message;
});
}
}
ngOnInit() {
}
}
|
Here we have written the service to call the api.
service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ConstantVariables } from '../_services/constants';
import { header } from '../_helpers/header';
@Injectable()
export class FileService {
constructor(private http: Http) { }
postFile(formData) {
return this.http.post(ConstantVariables.BASE_API_URL+'/file-upload',formData, header.formHead()).map((response: Response) => response.json());
}
}
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import { Headers, RequestOptions, Response } from '@angular/http';
export const header = Object.freeze({
// private helper methods
head() {
// create authorization header with token
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
let headers = new Headers();
if (currentUser && currentUser.result.userDetails.access_token) {
headers.append('authToken', currentUser.result.userDetails.access_token );
}
headers.append('Content-Type', 'application/json');
return new RequestOptions({ headers: headers });
},
formHead() {
// create authorization header with token
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
let headers = new Headers();
if (currentUser && currentUser.result.userDetails.access_token) {
headers.append('authToken', currentUser.result.userDetails.access_token );
}
return new RequestOptions({ headers: headers });
}
});
|
its not working