Angular7中的文件上传input type file不起作用

3

目前我正在使用Angular 7,但是无法使用

在Angular 6中,这个功能可以正常工作。

当提交文件类型的数据时,Angular 6会返回以下字段列表:

enter image description here

但是在Angular 7中,只能获取到文件路径,如下图所示:

enter image description here

我更新了Angular 6到Angular 7后出现了这个错误,但不知道具体问题所在。

谢谢


请提供源文本以便翻译 - Ebin Manuval
什么是错误? - Hrishikesh Kale
抱歉,这不是一个错误。在Angular 6中提交表单时,我会得到字段列表。而在Angular 7中只能获取图像路径,就像上面的图片一样。 - Anil
创建一个 StackBlitz。 - Ebin Manuval
您应该更新问题并附上您的 Stackblitz 链接,并在标题中包含“ReactiveForm”一词。 为了快速解决问题,您可以通过使用“change”输出来访问输入文件列表:<input #fileInput type="file" (change)="fileChange($event)>" 然后在控制器中 fileChange(event) { const fileList = event.target.files } 或者使用 @ViewChild('fileInput') fileInput => this.fileInput.nativeElement.files。 这样,您仍然可以使用您的 'image' formControl 进行验证,并在提交时检索文件列表。 - GeoAstronaute
显示剩余2条评论
2个回答

2

我在我的Angular应用程序中有一个上传文档部分,这是一个工作示例:

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);
      }
    );
  }

希望它能够帮到你,谢谢。


-1

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

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


虽然这段代码可能解决了问题,但是包括解释它如何以及为什么解决了问题将有助于提高您的帖子质量,并可能导致更多的赞。请记住,您正在回答未来读者的问题,而不仅仅是现在提问的人。请[编辑]您的答案以添加解释并指出适用的限制和假设。 - Yunnosch
目前你的回答不够清晰,请[编辑]以添加更多细节,帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接