user12217822
user12217822

Reputation: 302

How to upload a file in ngx dropzone in angular

Im using ngx-dropzone in angular 8. I don't know how can I upload a file instead of array.

html

<div class="custom-dropzone" ngx-dropzone [accept]="'image/*'" (change)="onSelect($event)">
<ngx-dropzone-label>
    <div>
        <h2>My custom dropzone</h2>
    </div>
</ngx-dropzone-label>
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f" [removable]="true" (removed)="onRemove(f)">
    <ngx-dropzone-label>{{ f.name }} ({{ f.type }})</ngx-dropzone-label>
</ngx-dropzone-image-preview>

ts

  files: File[] = [];

onSelect(event) {
    console.log(event);
    this.files.push(...event.addedFiles);
}

onRemove(event) {
    console.log(event);
    this.files.splice(this.files.indexOf(event), 1);
}

Upvotes: 2

Views: 9754

Answers (1)

Muthupriya
Muthupriya

Reputation: 345

I think you should have one way to achieve this. The ngx-dropzone npm module provide as a input of multiple [multiple] attribute but the one drawback of this module is they allow their files in array only. So, we need to remove the added files each time new file is uploaded.

[multiple]: Allow the selection of multiple files at once. Defaults to true.

HTML

 <ngx-dropzone (change)="onSelect($event)">
  <ngx-dropzone-label>Drop it, baby!</ngx-dropzone-label>
  <ngx-dropzone-preview *ngFor="let f of files" [multiple]='false' [removable]="true" (removed)="onRemove(f)" >
      <ngx-dropzone-label>{{ f.name }} ({{ f.type }})</ngx-dropzone-label>
  </ngx-dropzone-preview>
</ngx-dropzone>

Typescript

 
onSelect(event) {
  console.log(event);
  if(this.files && this.files.length >=2) {
    this.onRemove(this.files[0]);
  }
  this.files.push(...event.addedFiles);
}
 
onRemove(event) {
  console.log(event);
  this.files.splice(this.files.indexOf(event), 1);
}

Upvotes: 2

Related Questions