【问题标题】:Angular upload files form 3 inputs?角度上传文件形成 3 个输入?
【发布时间】:2019-01-08 05:22:48
【问题描述】:

我需要通过 3 个其他输入上传 3 个文件。 我是 Angular 的新手——如果这个问题很愚蠢,我很抱歉。

我的代码

BookFormComponent.ts:

export class BookFormComponent implements OnInit {
  audioFile: File = null;
  cueFile: File = null;
  coverFile: File = null;
  bookForm: FormGroup;

  constructor(
    private route: ActivatedRoute,
    private bookService: BookService,
    private formBuilder: FormBuilder
  ) {
  }

  ngOnInit() {
    this.createForm();
    this.pullBook();
  }

  pullBook() {
    const id = this.route.snapshot.paramMap.get('id');
    if (id != null) {
      this.bookService.get(id).subscribe(
        (book) => {
          this.bookForm.controls['title'].setValue(book.title);
          this.bookForm.controls['author'].setValue(book.author);
          this.bookForm.controls['description'].setValue(book.description);
        },
        error => console.log('error: ' + error) /* TODO : Change all console log */
      );
    }
  }

  createForm() {
    this.bookForm = this.formBuilder.group({
      title: [''],
      author: [''],
      description: [''],
      audio: [null],
      cue: [null],
      cover: [null]
    });
  }

  onFileSelected(number: number, event) {
    if (event.target.files && event.target.files.length) {
      console.log(event.target.files);
      switch (number) {
        case 0: {
          this.audioFile = event.target.files[0];
          this.bookForm.controls['audio']
            .setValue(this.audioFile ? this.audioFile.name : '');
          break;
        }

        case 1: {
          this.cueFile = event.target.files[1];
          this.bookForm.controls['cue']
            .setValue(this.cueFile ? this.cueFile.name : '');
          break;
        }

        case 2: {
          this.coverFile = event.target.files[2];
          this.bookForm.controls['cover']
            .setValue(this.coverFile ? this.coverFile.name : '');
          break;
        }
      }
    }
  }

  onSubmit() {
    const fd = new FormData();
    fd.append('author', this.bookForm.get('author').value);
    fd.append('title', this.bookForm.get('title').value);
    fd.append('description', this.bookForm.get('description').value);
    fd.append('finished', 'false');
    fd.append('audiobook', this.audioFile, this.audioFile.name);
    fd.append('cue', this.cueFile, this.cueFile.name);
    fd.append('cover', this.coverFile, this.coverFile.name);
    this.bookService.create(fd).subscribe(
      (book) => console.log(book),
      error => console.log(error)
    );
  }

}

BookFormComponent.html:

<div class="row">
  <div class="col-md-8 offset-md-2">
    <h3>Utwórz książkę</h3>
    <form [formGroup]="bookForm" (ngSubmit)="onSubmit()">
      <div class="form-group">
        <label for="title">Title</label>
        <input id="title"
               type="text"
               class="form-control"
               required
               name="title"
               formControlName="title">
      </div>

      <div class="form-group">
        <label for="author">Author</label>
        <input id="author"
               type="text"
               class="form-control"
               required
               name="author"
               formControlName="author">
      </div>

      <div class="form-group">
        <label for="description">Description</label>
        <input id="description"
               type="text"
               class="form-control"
               required
               name="description"
               formControlName="description">
      </div>

      <div class="form-group form-inline">
        <label class="btn btn-secondary btn-file">
          Audio
          <input name="audio" type="file" (change)="onFileSelected(0, $event)">
          <input type="hidden" name="audioHidden" formControlName="audio" required/>
        </label>

        <p *ngIf="audioFile" class="pl-4 align-middle mb-0">{{audioFile.name}}</p>
      </div>

      <div class="form-group form-inline">
        <label class="btn btn-secondary btn-file">
          Cue
          <input name="cue" type="file" (change)="onFileSelected(1, $event)">
          <input type="hidden" name="cueHidden" formControlName="cue" required/>
        </label>

        <p *ngIf="cueFile" class="pl-4 align-middle mb-0">{{cueFile.name}}</p>
      </div>

      <div class="form-group form-inline">
        <label class="btn btn-secondary btn-file">
          Cover
          <input name="cover" type="file" (change)="onFileSelected(2, $event)">
          <input type="hidden" name="coverHidden" formControlName="cover" required/>
        </label>

        <p *ngIf="coverFile" class="pl-4 align-middle mb-0">{{coverFile.name}}</p>
      </div>

      <button type="submit"
              class="btn btn-success"
              [disabled]="!bookForm.valid">
        Submit
      </button>

    </form>
  </div>
</div>

来自 'console.log(event.target.files);' 的文件列表的长度始终为 1。我想获取包含 3 个文件的列表 - 每个输入一个文件。我应该在我的代码中更改什么?

【问题讨论】:

    标签: angular


    【解决方案1】:

    你的函数在onFileSelected (number: number, event)上的问题在两种情况下,you have to take the index 0的File对象。

    不要认为它会是同一个文件,每次都会调用另一个实例,所以你总是需要索引 0。

    这样

    export class BookFormComponent implements OnInit {
      audioFile: File = null;
      cueFile: File = null;
      coverFile: File = null;
      bookForm: FormGroup;
    
      constructor(
        private route: ActivatedRoute,
        private bookService: BookService,
        private formBuilder: FormBuilder
      ) {
      }
    
      ngOnInit() {
        this.createForm();
        this.pullBook();
      }
    
      pullBook() {
        const id = this.route.snapshot.paramMap.get('id');
        if (id != null) {
          this.bookService.get(id).subscribe(
            (book) => {
              this.bookForm.controls['title'].setValue(book.title);
              this.bookForm.controls['author'].setValue(book.author);
              this.bookForm.controls['description'].setValue(book.description);
            },
            error => console.log('error: ' + error) /* TODO : Change all console log */
          );
        }
      }
    
      createForm() {
        this.bookForm = this.formBuilder.group({
          title: [''],
          author: [''],
          description: [''],
          audio: [null],
          cue: [null],
          cover: [null]
        });
      }
    
      onFileSelected(number: number, event) {
        if (event.target.files && event.target.files.length) {
          console.log(event.target.files);
          switch (number) {
            case 0: {
              this.audioFile = event.target.files[0];
              this.bookForm.controls['audio']
                .setValue(this.audioFile ? this.audioFile.name : '');
              break;
            }
    
            case 1: {
            //you have to do this
              this.cueFile = event.target.files[0];
              this.bookForm.controls['cue']
                .setValue(this.cueFile ? this.cueFile.name : '');
              break;
            }
    
            case 2: {
            //you have to do this
              this.coverFile = event.target.files[0];
              this.bookForm.controls['cover']
                .setValue(this.coverFile ? this.coverFile.name : '');
              break;
            }
          }
        }
      }
    
      onSubmit() {
        const fd = new FormData();
        fd.append('author', this.bookForm.get('author').value);
        fd.append('title', this.bookForm.get('title').value);
        fd.append('description', this.bookForm.get('description').value);
        fd.append('finished', 'false');
        fd.append('audiobook', this.audioFile, this.audioFile.name);
        fd.append('cue', this.cueFile, this.cueFile.name);
        fd.append('cover', this.coverFile, this.coverFile.name);
        this.bookService.create(fd).subscribe(
          (book) => console.log(book),
          error => console.log(error)
        );
      }
    
    }

    【讨论】:

    • 哇!有用。谢谢 :) 现在我知道我做错了什么 - 我没有将 event.target.files[0] 视为单个事件文件。
    • 很高兴它可以工作。可能你忘了把索引设为 0。现在你可以批准解决方案,让其他人看到解决方案。
    猜你喜欢
    • 2015-03-25
    • 2022-01-16
    • 1970-01-01
    • 2015-10-02
    • 2018-06-04
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多