【发布时间】:2018-10-29 12:56:21
【问题描述】:
我在使用 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": ""
}]
如何更正代码以解决问题?
【问题讨论】:
-
一个现已删除的答案pointed here。
标签: angular