使用角度材料上传文件5

时间:2018-05-21 20:40:49

标签: file-upload angular-material angular5

我尝试使用角度材质5上传文件(角度5)。

app.component.html

    <mat-horizontal-stepper [linear]="isLinear" #stepper="matHorizontalStepper">

  <mat-step [stepControl]="firstFormGroup">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Upload your audio file</ng-template>
      <mat-form-field>
          <input matInput  
          style="display: none" 
          type="file" (change)="onFileSelected($event)" 
          #fileInput name ="file" formControlName="firstCtrl" required>
      <button mat-button (click)="fileInput.click()" >Select File</button>
  </mat-form-field>
  <div>
    <button mat-button matStepperNext>Next</button>
  </div>
</form>

app.component.ts

export class AppComponent {
  selectedFile: File=null;
  isLinear = true;
  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  constructor(private _formBuilder: FormBuilder, private http: HttpClient) {}
  ngOnInit() {
   this.firstFormGroup = this._formBuilder.group({
     firstCtrl: ['', Validators.required]
    });
   this.secondFormGroup = this._formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }

但是我收到了这个错误

ERROR Error: Input type "file" isn't supported by matInput.

知道这些代码在没有角度材料的情况下运行良好有什么问题吗?

2 个答案:

答案 0 :(得分:0)

  

使用更快的解决方案   https://github.com/danialfarid/ng-file-upload

<md-button class='md-raised md-primary' id='uploadFile' ngf-multiple='true' ngf-select='upload($files, $file, $event)'
     

type ='file'>           上传文件       

     

否则,您将不得不使用这样的自定义代码:

<label class="md-secondary md-raised md-button" md-ink-ripple for="input-file">
      <span>Select File to upload</span>
</label>
<input type="file" ngf-select ng-model="input-file" name="input-file" id="input-file">

已编辑

在您的HTML中:

 <input #file type="file" nbButton multiple (change)="upload(file.files)" /> 

然后在您的组件中:

upload(files: any) {
    this.yourServiceToUploadFiles.uploadFile(files).subscribe(
      (response: any) => { .......})}

然后为您服务:

uploadFile(files: any[]): Observable<HttpResponse<Blob>> {
    if (files.length === 0) {
      return;
    }

    const formData = new FormData();
    for (const file of files) {
      formData.append(file.name, file);
    }

    return this.http.post(`${apiUrl}/yourServiceEndPoint`, formData, {
      observe: "response",
      responseType: "blob"
    });
  }

答案 1 :(得分:0)

我遇到了同样的问题,

尝试这样做,

    <button mat-raised-button (click)="openInput()">Select File to Upload</button>
    <input id="fileInput" hidden type="file" (change)="fileChange($event.target.files)" name="file" accept=".csv,.xlsv">

  openInput(){ 
        document.getElementById("fileInput").click();
   }

上面的代码只是创建一个Material按钮,然后调用openInput()方法,稍后将其替换为下面的HTML代码

<input id="fileInput" hidden type="file" >

这对我有用。

快乐编码☻