首页 > 解决方案 > 如何使用 Angular 上传相同的文件?

问题描述

我使用以下代码在 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)第三次打开窗口时(在我第二次选择相同的文件并且没有发生任何事情之后)并在不选择任何文件的情况下关闭它,uploadRenewals()被调用并console显示以下错误:

ERROR TypeError: Cannot read property 'name' of null

知道发生了什么以及如何解决这个问题吗?

标签: angular

解决方案


解释 :

您需要的是在每次上传后清除输入文件元素,如果您关闭对话框并且使用空事件触发事件(更改) ,那么当涉及到这一行时,第二个问题是:

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>

推荐阅读