Friday, 19 January 2018

File upload validation - Angular

AngularFile UploadValidation

In this article we will be discussing about validating a file/image from client side before uploading. In my previous articles I have covered file upload and showing a preview image while uploading, now let us check the validation part.

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;
        //check file is valid
        if (!this.validateFile(files[0].name)) {
            console.log('Selected file format is not supported');
            return false;
        }

        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 => console.log(response),
            error => console.log(error)
        )
    }
}

Validation


validateFile(name: String) {
    var ext = name.substring(name.lastIndexOf('.') + 1);
    if (ext.toLowerCase() == 'png') {
        return true;
    }
    else {
        return false;
    }
}

Here we are taking the file/image extension and validating before uploading to backend. Similar way you can check other extensions as well.


if (ext.toLowerCase() == 'war')
if (ext.toLowerCase() == 'csv')
if (ext.toLowerCase() == 'jpeg')
...etc

We are done. In this article we have discussed about validating a file/image before uploading to backend.

Angular 2+Angular 4/5File UploadValidation

Related Info

1. File/Image upload validation- Angular

2. File/Image upload and send data to backend

3. Show preview image while uploading file/image

4. Rating star component - Angular

5. Date filtering and formatting - Angular

Thursday, 18 January 2018

File upload and send data to backend - Angular

AngularFile 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 2+Angular 4/5File UploadImage Upload

Related Info

1. File/Image upload validation- Angular

2. File/Image upload and send data to backend

3. Show preview image while uploading file/image

4. Rating star component - Angular

5. Date filtering and formatting - Angular

Wednesday, 17 January 2018

Show preview image while uploading - Angular

AngularPreview imageUpload

In this article we are going to discuss about showing a preview image while uploading. This can be achieved by using very less code. Let's check below example

Preview image while uploading



import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<input type="file" (change)="showPreviewImage($event)">'
        + '<img [src]="localUrl" *ngIf="localUrl" class="imgPlaceholder">'
        + '</div>',
})

export class AppComponent {
    localUrl: any[];
    constructor() { }
    showPreviewImage(event: any) {
        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.onload = (event: any) => {
                this.localUrl = event.target.result;
            }
            reader.readAsDataURL(event.target.files[0]);
        }
    }
}

While clicking on showPreviewImage method we are taking the selected image url and assigning to localUrl. We can a show a preview image and upload the selected file/image to backend as well. Check this link for that: - File upload and send data to backend. Here I have used *ngIf to hide the preview image section until it is available. You can do more things using Angular 4 ngIf. Check the difference between Angular 2 ngIf and Angular 4 ngIf here.

We are done. You can use css to improve the look and feel. In this article we have discussed about showing a preview image while uploading.

Angular 2+Angular 4/5Preview imageUpload

Related Info

1. File/Image upload validation- Angular 4

2. File/Image upload and send data to backend

3. Rating star component - Angular 4

4. Date filtering and formatting - Angular 4