Thursday, January 18, 2018

File upload and send data to backend - Angular 4

Angular 4File UploadImage Upload

In this article we will be discussing about how to upload a file/image and send data to backend. In my previous article I have explained about showing a preview image while uploading a file/image. Let us start by creating a simple component.

Component


import { Component } from '@angular/core';
import { commonService } from './services/commonService'

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<input type="file" (change)="upload($event)">'
        + '</div>',
})

export class AppComponent {

    constructor(private _service: commonService) { }

    upload(event: any) {
        let files = event.target.files;
        let fData: FormData = new FormData;

        for (var i = 0; i < files.length; i++) {
            fData.append("file[]", files[i]);
        }
        var _data = {
            filename: 'Sample File',
            id: '0001'
        }

        fData.append("data", JSON.stringify(_data));

        this._service.uploadFile(fData).subscribe(
            response => this.handleResponse(response),
            error => this.handleError(error)
        )
    }
    handleResponse(response: any) {
        console.log(response);
    }
    handleError(error: string) {
        console.log(error);
    }
}

Upload method will capture the file parameter and you can append the data as well along with that. We are passing these details to a service file. Check below code for that.

Service file


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';


@Injectable()
export class commonService {
    _url: string;
    constructor(private http: Http) { }

    uploadFile(data: any): Observable<{}> {
        this._url = 'http://localhost:4200/XXXXXXXXXX/uploadFile';
        return this.http.post(this._url, data)
            .map(this.handleData)
            .catch(this.handleError);
    }

    private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
}

You can use your own api depends on your backend code (Java, .Net etc.). We are passing byte array to backend. If you don't want to add additional parameters you can just pass only file data. Click on the button and test the file upload code by linking your backend code. If you want to show preview image while uploading refer this link. I have used angular http to make an API call, you can read more about angular http request calls here. Depends on your backend code you may need to pass some headers along with your http calls. Refer this link to know about passing headers along with http calls.

In this article we have discussed about uploading a file/image and sending data to backend.

Angular 4File UploadImage Upload

Related Info

1. File/Image upload validation- Angular 4

2. File/Image upload and send data to backend

3. Show preview image while uploading file/image

4. Rating star component - Angular 4

5. Date filtering and formatting - Angular 4

No comments :

Post a Comment