Monday 14 May 2018

Angular 2 provides good support for uploading file


Angular 2 provides good support for uploading file. Any third party library is not required.

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">

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);
        let headers = new Headers();
        /** In Angular 5, including the header Content-Type can invalidate your request */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(`${this.apiEndPoint}`, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}
using @angular/core": "~2.0.0" and @angular/http: "~2.0.0"

Ref:
https://www.blogger.com/blogger.g?blogID=4795707642151153385#editor/target=post;postID=5393771942504813896

No comments:

Post a Comment