1

upload function: I want to bind file/image , how it possible? I dont know how to pass form data in argument

  upload() {
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    let formData = new FormData();
    console.log(formData)
    if (fileCount > 0) { // a file was selected
        for (let i = 0; i < fileCount; i++) {
            formData.append('file[]', inputEl.files.item(i));
        }
        this.http
            .post(this.uploadUrl, formData)
             .subscribe(
            data => {
                alert ('Update successful');
            },
            error => {
                alert  ('Not updated');
                this.loading = false;
            });
    }

HTML component :

<form>
 <div>
      <input type="file" [multiple]="multiple" #fileInput>
      <button type="button" (click)="upload()">Upload</button>
 </div>
</form>
Krunal
  • 938
  • 2
  • 10
  • 33

1 Answers1

0
 <input type="file" (change)="fileChange($event)" placeholder="Upload 
 file" accept=".pdf,.doc,.docx">

fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
    let file: File = fileList[0];
    let formData:FormData = new FormData();
    formData.append('uploadFile', file, file.name);
    let headers = new Headers();
    /** No need to include Content-Type in Angular 4 */
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post(`${this.apiEndPoint}`, formData, options)
        .map(res => res.json())
        .catch(error => Observable.throw(error))
        .subscribe(
            data => console.log('success'),
            error => console.log(error)
        )
}

}

Krunal
  • 938
  • 2
  • 10
  • 33