简体   繁体   中英

How to upload only one file on a server in Angular?

I want to upload a file on a server using Angular. I used this link: https://malcoded.com/posts/angular-file-upload-component-with-express to attach multiple files.

But I want to attach only one file and upload only one file. Here is my code:

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>

I want the user to only be able to attach one file, if the user tries to attach again, the first attachment should be removed and only the latest attached file should be shown.

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

This is an example Stackblitz which demonstrating how to make a component upload file.

The idea is having an input to receive the file

HTML : Add yourself the stuff malcoded

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

Then, upload it

Component

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM