0

I'm beginner for the Angular, I want to know how to create Angular-6 File upload part. I need to send uploaded angular file to API. I've tried below code and it didn't work for me. I'm using angular forms. I've tried this code from here.

upload.component.html

<mat-card>
 <mat-card-title>Upload Files</mat-card-title>
 <mat-card-subtitle></mat-card-subtitle>
   <form [formGroup]="form" (ngSubmit)="onSubmit()">
   <mat-card-content>
     <div fxLayout="row" fxLayoutWrap="wrap">
       <div fxFlex.gt-sm="80%" fxFlex.gt-xs="50" fxFlex="100">
         <div class="mb-1">
           <input type="file"  id="file" formControlName="file 
             (change)="handleFileInput($event.target.files)">
         </div>
        </div>
      </div>
  </mat-card-content>
  <mat-card-actions class="px-1">
    <button mat-raised-button color="primary" type="submit 
    [disabled]="!form.valid">Submit</button>
  </mat-card-actions>
 </form>
 <div class="container">
  <router-outlet></router-outlet>
 </div>
</mat-card>

upload.component.ts

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file- 
 upload';
import { Router, ActivatedRoute } from "@angular/router";
import { UploadService } from "../upload.service";
import { FormBuilder, FormGroup, Validators, FormControl } from 
 '@angular/forms';

@Component({
 selector: 'app-upload',
 templateUrl: './upload.component.html',
 styleUrls: ['./upload.component.css']
})
export class UploadComponent{
 title = 'upload';
 public form: FormGroup;
 errorMessage: string;

constructor(
 private router: Router,
 private uploadService: UploadService,
 private fb: FormBuilder
) {}

fileToUpload: File = null;

handleFileInput(files: FileList) {
  this.fileToUpload = files.item(0);
}

ngOnInit() {
  this.form = this.fb.group({
  file: null
});
}

onSubmit(){
  const newFile = this.fileToUpload;
  this.uploadService.uploadFile(newFile)
    .subscribe(data => {
          if (data) {
              alert('File uploaded successfully');
          } else {
              alert('Error Uploading File');
          }
      },
      error => { this.errorMessage = <any>error }
  );
}

}

upload.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import "rxjs-compat/add/operator/map";
import {e} from "@angular/core/src/render3";

const httpOptions = {
  headers: new HttpHeaders({'Authorization': localStorage.getItem('token')})
};

@Injectable({
  providedIn: 'root'
})

export class UploadService {
  private uploadUrl = 'http://localhost:3000/api/upload';

 constructor(
   private http: HttpClient,
 ) { }

 uploadFile(fileToUpload: File): Observable<boolean> {
   const formData: FormData = new FormData();
   formData.append('fileKey', fileToUpload, fileToUpload.name);
   return this.http.post(this.uploadUrl, formData, httpOptions)
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
 }
}

Can anyone please help me? Thanks a lot

0 Answers0