Angular 2上传多个文件

时间:2016-09-21 06:07:18

标签: html angular

我尝试上传多个文件(PDF或各种图片格式)。现在上传单个文件有效,但多个不起作用。

这是代码:

HTML:

private void btnUpdate_Click(object sender, EventArgs e)
    {
        int id = 0;            
        id = Convert.ToInt32(lblId.Text);               
        foreach (var dgr in gridViewCompanies.Rows)
        {
            if (dgr.Cells[0].Value.Equals(tbl.ID))
            {
                dgr.IsSelected = true;
                dgr.Cells[0].IsSelected = true;GridTableElement tableElement = this.gridViewCompanies.CurrentView as GridTableElement;
                        tableElement.ScrollToRow(dgr.Index);

                break;
            }
        }
     }

脚本:

<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>

帮我看看如何上传多个文件。

3 个答案:

答案 0 :(得分:10)

multiple属性添加到您的输入中:

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

要显示输入中的所有文件名,请在此插件中执行此操作: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 {}

或者使用你的变量而不是直接将它放到那个输入上!

答案 1 :(得分:1)

你可以试试这对我有用;)

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

答案 2 :(得分:1)

初始化:

selectedFiles: File[];

文件选择事件:

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

提交表单事件:

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

HTML文件输入:

<input 
 type="file" 
 id="documents" 
 multiple
 formControlName="documents" 
 (change)="onFileSelected($event)"
 accept="image/*,.pdf,.doc,.docx,.xml">