1

I am quite new to Angular 2, please consider it.

I am facing a problem with uploading a file to the node server using angular 2. It works fine using postman:

Postman snapshot:

enter image description here

However, when I use the Angular2 application to send a file to the server, it does nothing:

Angular HTML Component

<label for="file1">Upload PDF version: </label>
<form class="form-inline">
    <div class="form-group">
        <input type="file" id="file1" #abc name="fileToUpload"  class="form-control" placeholder="Upload PDF">
    </div>
    <button class="btn btn-primary" type="submit" (click)="onUpload(abc)">Upload</button>
</form>

Angular TS component:

import { Component, OnInit } from '@angular/core';
import { UploadService } from './upload.service';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {

  // file1 = document.getElementById("file1");
  constructor(private uploadService: UploadService) { }

  ngOnInit() {
  }

  onUpload = (file: File) => {
    this.uploadService.uploadfile(file)
      .subscribe((res) => {
        console.log(res);
      },

        (err) => {
          console.log(err);
        });
  }

}

Service component:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';


@Injectable()
export class UploadService {

  constructor(private http: HttpClient) {
  }

  uploadfile(file: File): Observable<File> {

    console.log(file);
    return this.http.post<File>("http://localhost:3000/fileupload", file, { headers: { 'Content-Type': 'application/json' } });
  }

}

Of course, I must be missing something here. I request you all, to please provide some solution.

MasOOd.KamYab
  • 944
  • 11
  • 25
Raj
  • 77
  • 2
  • 5

2 Answers2

2

You have to create formData to upload file. Below is the sample code.

      fileDetails: any = {
        clientDoc: {}
      }; 
      uploadClientDoc(event) {
        this.fileDetails.clientMandateForm = event.srcElement.files[0];
        this.submitFlag = this.fileDetails.isdaFile ? true : false;
      }

      submit() {
        let formData: FormData = new FormData();
        formData.append('clientDoc', this.fileDetails.clientDoc);
        var data = this.urService.uploadFiles(formData).subscribe(res => {
          //your login  
        });

      }



      uploadFiles(data) {
        const httpOptions = {
          headers: new HttpHeaders({        
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'multipart/form-data' 
          })
        };

        return this.http.post('<url>', data, httpOptions);
      }






       <div>
        <label>Please Select Document</label>
        <label class="type-file">+ Upload FIle
          <input type="file" accept="application/pdf" id="my_file1" (change)="uploadClientDoc($event)" />
        </label>   
        <label >{{fileDetails.clientDoc.name}}</label>
      </div>

      <button class="ci-btn float-right-btn" type="button"  (click)="submit()" value="Submit">Submit</button>
Lakshmi Prasanna
  • 440
  • 4
  • 16
0

i think your issue is about Headers.

try this :

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';


@Injectable()
export class UploadService {

  constructor(private http: HttpClient) {
  }

  uploadfile(file: File): Observable<File> {

    console.log(file);
    return this.http.post<File>("http://localhost:3000/fileupload", file, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
  }

}

If you check your PostMan screenshot, is exact same header provided. Is common way to upload File

Yanis-git
  • 7,737
  • 3
  • 24
  • 41