Anil
Anil

Reputation: 148

angular7 input type file upload not working

Present i'm working angular angular 7 input type="file" not working.

Angular6 its working fine.

angular 6 submit the input file type data

i will get field list like this

enter image description here

But angular 7 only get image path like this.

enter image description here

only i updated angular 6 to angular 7 i will get this error. what is the issue i don't know.

Thanks,

Upvotes: 3

Views: 7661

Answers (2)

Saruf Ratul
Saruf Ratul

Reputation: 1

var selectedElement: File = (document.getElementById(id) as HTMLElement).files[0] as File;

Upvotes: -1

rcanpahali
rcanpahali

Reputation: 2643

I have a upload document section in my Angular app, here is working example:

example.component.html

<form [formGroup]="form">
<div class="form-group">
    <label>Select file to upload.</label>
    <input type="file" id="bannedList" (change)="onFileChange($event);" #fileInput>
</div>
</form>
<button type="button" (click)="onSubmit();" [disabled]="!fileInput.value" class="btn btn-success pull-right"><i class="fa fa-save fa-fw"></i> Upload File</button>

example.component.ts

import { Component, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";

...

export class exampleUploadComponent implements OnInit, OnDestroy {
  public form: FormGroup;
  @ViewChild('fileInput', { read: ElementRef }) private fileInput: ElementRef;

...

  createForm() {
    this.form = this.fb.group({
      bannedList: null
    });
  }

  onFileChange(event) {
    this.uploadStatus = 0;
    if (event.target.files.length > 0) {
      let file = event.target.files[0];
      this.form.get('bannedList').setValue(file);
    }
  }

  private prepareSave(): any {
    let input = new FormData();
    input.append('bannedChequeCustomersFile', this.form.get('bannedList').value);
    return input;
  }

  onSubmit() {
    const formModel = this.prepareSave();
    this.uploadChequeSubscription = this.chequeOperationService.uploadBannedChequeList(formModel).subscribe(
      (res) => {
        console.log("res handler:", res);
      },
      (err) => {
        console.log("err handler:", err);
      }
    );
  }

I hope it will help, thanks.

Upvotes: 2

Related Questions