【问题标题】:How to upload only one file on a server in Angular?如何在 Angular 的服务器上只上传一个文件?
【发布时间】:2018-08-09 14:35:47
【问题描述】:

我想使用 Angular 在服务器上上传文件。 我使用了这个链接: https://malcoded.com/posts/angular-file-upload-component-with-express 附加多个文件。

但我只想附加一个文件并上传一个文件。 这是我的代码:

https://stackblitz.com/edit/angularizjqax?file=src%2Fapp%2Fupload%2Fdialog%2Fdialog.component.html

<input type="file" #file style="display: none" (change)="onFilesAdded()"/>
<div class="container" fxLayout="column" fxLayoutAlign="space-evenly stretch">
  <h1 mat-dialog-title>Upload Files</h1>
  <div>
    <button [disabled]="uploading || uploadSuccessful" mat-raised-button color="primary" class="add-files-btn" (click)="addFiles()">
      Add Files
    </button>
  </div>

  <!-- This is the content of the dialog, containing a list of the files to upload -->
  <mat-dialog-content fxFlex>
    <mat-list>
      <mat-list-item *ngFor="let file of files">
        <h4 mat-line>{{file.name}}</h4>
        <mat-progress-bar *ngIf="progress" mode="determinate" [value]="progress[file.name].progress | async"></mat-progress-bar>
      </mat-list-item>
    </mat-list>
  </mat-dialog-content>

  <!-- This are the actions of the dialog, containing the primary and the cancel button-->
  <mat-dialog-actions class="actions">
    <button *ngIf="showCancelButton" mat-button mat-dialog-close>Cancel</button>
    <button mat-raised-button color="primary" [disabled]="!canBeClosed" (click)="closeDialog()">{{primaryButtonText}}</button>
  </mat-dialog-actions>
</div>

我希望用户只能附加一个文件,如果用户再次尝试附加,则应删除第一个附件,只显示最新附加的文件。

https://stackblitz.com/edit/angular-izjqax?file=src%2Fapp%2Fupload%2Fdialog%2Fdialog.component.html

【问题讨论】:

  • 有什么问题?
  • 我可以附加多个文件,但我只需要附加一个文件
  • 我希望用户只附加一个文件,如果用户尝试再次附加它,它会删除第一个并显示最新的附加文件

标签: javascript angular file-upload


【解决方案1】:

这是一个示例Stackblitz,它演示了如何制作组件上传文件。

这个想法是有一个输入来接收文件

HTML : 添加错误代码

<h1 mat-dialog-title>Upload Files</h1>
  <div>
    <input type="file" (change)="selFile($event.target.files)">
  </div>
  <button (click)="startUpload()">Upload</button>

然后上传

组件

  selectedFile: any;
  selFile(event: FileList) {
    this.selectedFile = event.item(0);
  }
  startUpload() {
    const file = this.selectedFile;
    //call web service to upload
  }

【讨论】:

  • 你能换我的link
  • 你能分享一下stackblitz吗
  • @user944513 很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 2015-12-02
  • 1970-01-01
  • 2020-11-13
相关资源
最近更新 更多