首页 > 解决方案 > 文件输入转换按钮转换为 Angular 中带有文件名的上传按钮

问题描述

I want to upload a file with a browse button and when the file is selected the browse button should go away and instead an upload button should come adjacent to the file name selected.

我应该如何在 Angular 6 中做到这一点?

这是我到目前为止所做的。已经制作了第一个屏幕。

HTML

  <div class="pr-3 pt-2">
    <h4>Choose an excel file to upload</h4>
  </div>
  <div>
    <label for="upload" class="file-upload-label">Browse</label>
    <input type="file" placeholder="Upload file" accept=".xlsx" (change)="incomingfile($event)" class="file-upload-input" id="upload">
  </div>

传入文件事件函数

 incomingfile(event) {
    this.file = event.target.files[0];
    this.filePresent = true;
  }

图片供您参考

标签: javascriptcssangularfile-uploadangular6

解决方案


基本逻辑 -----> DEMO

HTML:

<div class="pr-3 pt-2">
    <h4>Choose an excel file to upload</h4>
</div>
<label *ngIf="!filePresent">
            <input #fileInput  type="file" (change)="incomingfile($event)" />
            <span>Browse File</span>
</label>
<label *ngIf="filePresent">
            <label >{{fileName}}</label>
<button (click)="uploadFile()"><span> Upload</span></button>
</label>

TS:

  file: File;
  filePresent: boolean = false;
  fileName: string = ''

  incomingfile(event) {
    this.file = event.target.files[0];

    this.fileName = this.file.name;

    this.filePresent = true;
  }

  uploadFile() {
    if (this.file) {
      console.log(this.file);
    }
  }

推荐阅读