File Upload Tutorial with Angular 6

Angular 6 File Upload Tutorial. In this example, We will use an ng2-file-upload library to upload a file to the server. We use Laravel as a backend server. We install Angular 6 using Angular CLI and then start working on this Angular File Upload demo. For managing the uploaded files at the backend.

So I hope you have already installed angular 6 on your machine.

Step 1: Install rxjs-compat library.
Since third-party libraries do not support the RxJS 6. Now, one change in Angular 6 is that Angular 6 now depends on TypeScript 2.7 and RxJS 6. So, if you install third-party packages right now, then it is not compatible with Angular 6. In future, all the third-party libraries might upgrade their packages, but right now, it is not compatible with Angular 6.

So, to fill the gap between Angular 6 and third-party packages, we need to install the following library. That is it.

npm install rxjs-compat --save

Step 2: Install ng-file-upload library

Type the following command to install the library.

npm install ng2-file-upload --save

Now, write the following code inside an app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FileSelectDirective } from 'ng2-file-upload';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    FileSelectDirective
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Okay, so we have imported FormsModule and FileSelectDirective.

Now, write the following code inside an app.component.ts file.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';

const URL = 'http://localhost:3000/api/upload';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'});

  ngOnInit() {
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
         console.log('ImageUpload:uploaded:', item, status, response);
         alert('File uploaded successfully');
     };
 }
}

Finally, write the following code inside an app.component.html file.

<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />

<button type="button" class="btn btn-success btn-s" 
  (click)="uploader.uploadAll()" 
  [disabled]="!uploader.getNotUploadedItems().length" >
      Upload an Image
</button>

Step 6: Create Laravel Backend Function to Receive File

 public function uploadProfilePhoto(Request $request) {
        //To get the file name: $request->file('file')->getClientOriginalName()
        //To get the file type: $request->file('file')->extension()
        //To get the file size: $request->file('file')->getClientSize()
        $fileinfo = array(
            'name' => $request->file('file')->getClientOriginalName(),
            'type' => $request->file('file')->extension(),
            'size' => $request->file('file')->getClientSize(),
        );
        //To move file in to you project directory
        $request->file('file')->move(__DIR__ . '/../../../', time().'.'.$fileinfo['name'] . '.' . $fileinfo['type']);
        //To show the response by this way if you are working with laravel api.
        return response()->json(['errors' => [], 'files' => $fileinfo, 'status' => 200], 200);
 }

Thanks 🙂

For more: angular-6-file-upload-tutorial

You May Also Like

About the Author: Jafor Iqbal

Leave a Reply