user944513
user944513

Reputation: 12729

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

Upvotes: 0

Views: 1805

Answers (1)

Antoine V
Antoine V

Reputation: 7204

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
  }

Upvotes: 1

Related Questions