Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 upload multiple files

Tags:

html

angular

I trying to upload multiple files (PDFs or various image formats). Right now uploading a single file works, but multiple does not.

This is the code:

HTML:

<div>
    <label> Upload PDF(s) or Images (PNG/JPG/DICOM/DCM):</label>
    <div class="ctrl">
        <div class="icon">
            <i class="fa fa-file-image-o"></i>
        </div>
        <input type="file" (change)="onChange($event)"/>
        <md-input class="ctrl" [(ngModel)]="fileName"></md-input>
    </div>
</div>

Script:

onChange(event: any) {
    this.fileName = event.srcElement.files[0].name;
}

Help me how to do multiple files upload.

like image 285
Nagarjuna Reddy Avatar asked Sep 21 '16 06:09

Nagarjuna Reddy


People also ask

How can I limit the size of attachment file upload in angular?

You can restrict the maximum allowed file size (in bytes) by using the maxFileSize property. If the selected file exceeds the maximum size, an error message will be displayed.


3 Answers

Add the multiple attribute to you input:

<input type="file" (change)="onChange($event)" multiple />

And to show all file names in your input, do it like in this plunker: https://plnkr.co/edit/WvkNbwXpAkD14r417cYM?p=preview

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <input type="file" multiple (change)="onChange($event, showFileNames)" />
      <input #showFileNames />
    </div>
  `,
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }

  onChange(event: any, input: any) {
    let files = [].slice.call(event.target.files);

    input.value = files.map(f => f.name).join(', ');
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Or use your variable instead of putting it directly to that input!

like image 90
slaesh Avatar answered Oct 22 '22 13:10

slaesh


you can try this it worked for me ;)

https://github.com/jkuri/ng2-uploader

like image 41
Atul Bhalerao Avatar answered Oct 22 '22 12:10

Atul Bhalerao


Initialization:

selectedFiles: File[];

Files Selection Event :

onFileSelected(event) {
  this.selectedFiles = event.target.files;
  for (let i = 0; i < event.target.files; i++) {
    this.selectedFiles.push(event.target.files[i]);
  }
}

Form Submission Event :

onSubmit() {
  const formData = new FormData();
  if (this.selectedFiles.length > 0) {
   for (const row of this.selectedFiles) {
     formData.append('document_files[]', row);
   }
  }
}

HTML File Input :

<input 
 type="file" 
 id="documents" 
 multiple
 formControlName="documents" 
 (change)="onFileSelected($event)"
 accept="image/*,.pdf,.doc,.docx,.xml">
like image 34
Mohd Abdul Baquee Avatar answered Oct 22 '22 12:10

Mohd Abdul Baquee