Как загрузить тот же файл, используя Angular? - PullRequest
0 голосов
/ 19 февраля 2020

Я использую следующий код для загрузки файла в Angular:

HTML

<div class="form-group">
 <label for="file">Choose File</label>
 <input type="file"
       id="file"
       (change)="uploadRenewals($event.target.files)">
</div>

Машинопись

fileToUpload: File = null;

uploadRenewals(files: FileList) {
  console.log('Uploading starts...', files);
  const formData: FormData = new FormData();
  this.fileToUpload = files.item(0);
  formData.append('file', this.fileToUpload, this.fileToUpload.name);
  this._docService.uploadRenewals(formData)
    .pipe(take(1))
    .subscribe((response: RenewalsResponse) => {
    console.log('Response is', response);
   }, (error) => {console.log(error);});

Служба

uploadRenewals(formData: FormData) {
 return this._http.post(this.baseUrl + '/docs/uploadRenewals', formData, { responseType: 'json' })
 .catch(this.errorHandler);
}

Дело в том, что это работает, когда я каждый раз загружаю другой файл, но когда я пытаюсь загрузить один и тот же файл, ничего не запускается и функция uploadRenewals() никогда не вызывается.

Также я заметил, что когда я открываю окно (change)="uploadRenewals($event.target.files) в третий раз (после того, как я выбрал тот же файл во 2-й раз, и ничего не произошло) и закрываю его без выбора какого-либо файла, вызывается uploadRenewals() и в console отображается следующая ошибка:

ERROR TypeError: Cannot read property 'name' of null

Есть идеи, что происходит и как это исправить?

1 Ответ

1 голос
/ 19 февраля 2020

ОБЪЯСНЕНИЕ:

Вам нужно очищать входной файл Element после каждой загрузки и для второй проблемы, если вы закрываете диалоговое окно и событие (изменить) запускается с пустым событие, когда дело доходит до этой строки:

formData.append('file', this.fileToUpload, this.fileToUpload.name);

this.fileToUpload пусто.

РЕШЕНИЕ:

TS:

import {
  Component,
  OnInit,
  ViewChild,
  ElementRef
} from '@angular/core';

@ViewChild('fileInput', {
    static: false
}) fileInput: ElementRef;
fileToUpload: File = null;

uploadRenewals(files: FileList) {
    console.log('Uploading starts...', files);
    const formData: FormData = new FormData();
    this.fileToUpload = files.item(0);
    if (this.fileToUpload) { // this condition to avoid your the error that you mentioned
        formData.append('file', this.fileToUpload, this.fileToUpload.name);
        this._docService.uploadRenewals(formData)
            .pipe(take(1))
            .subscribe((response: RenewalsResponse) => {
                console.log('Response is', response);
                this.fileInput.nativeElement.value = null; //this clears the input file to let the event (change) fire again so you can upload the same file again
            }, (error) => {
                console.log(error);
            });
    }
}

HTML:

<div class="form-group">
 <label for="file">Choose File</label>
 <input #fileInput type="file"
       id="file"
       (change)="uploadRenewals($event.target.files)">
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...