使用Angular 4进行多文件上传

时间:2018-05-19 05:49:11

标签: angular

我正面临使用Angular 4上传多个文件的问题。

这里我试图将多个文件附加到getFileDetails()中,但只有文件正在选择,如果我选择另一个文件,它会被新文件替换,但实际期望是否需要追加彼此并使用post方法我需要传递json。

app.component.html:

    <div>
      <h1>{{title}}!</h1>
    <ng-container>
          <input type="file" id="file" multiple (change)="getFileDetails($event)">
           <button (click)="uploadFiles()">Upload</button>
      </ng-container>
    </div

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http/src/response';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Upload Multiple Files in Angular 4';

  constructor (private httpService: HttpClient) {  }


  ngOnInit () {  }
  myFiles:string [] = [];
  sMsg:string = '';

  getFileDetails (e) {
    //console.log (e.target.files);
    for (var i = 0; i < e.target.files.length; i++) { 
      this.myFiles.push(e.target.files[i]);
    }
  }

  uploadFiles () {
    const frmData = new FormData();

    for (var i = 0; i < this.myFiles.length; i++) { 
      frmData.append("fileUpload", this.myFiles[i]);
    }

    this.httpService.post('url', frmData).subscribe(
      data => {
        // SHOW A MESSAGE RECEIVED FROM THE WEB API.
        this.sMsg = data as string;
        console.log (this.sMsg);
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);    // SHOW ERRORS IF ANY.
      }
    );
  }
}
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http';

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

预期json:

[{
   "attachmentName": "content-infographic.txt",
   "attachedFile": ""
},
{
  "attachmentName": "infographic.png",
   "attachedFile": ""
}]

如何更正代码以解决问题?

2 个答案:

答案 0 :(得分:0)

我在PHP API中使用了以下内容,使append函数的第一个参数成为字符串数组。像这样在循环中替换它:

frmData.append("fileUpload[]", this.myFiles[i]);

唯一的变化是添加了方括号。

答案 1 :(得分:0)

只需按当前日期自动重命名文件,然后再将其上传到服务器上,请使用以下代码

var d = new Date();
var msec = Date.parse(d);
for (var i = 0; i < this.myFiles.length; i++) { 
   frmData.append("fileUpload", this.myFiles[i], this.myFiles[i].name + msec);
}