使用 Angular 4 上传多个文件

问题描述 投票:0回答:2

我面临使用 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": ""
}]

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

angular
2个回答
0
投票

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

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

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


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);
}
© www.soinside.com 2019 - 2024. All rights reserved.