【发布时间】:2020-12-02 22:58:45
【问题描述】:
我在 Angular 应用程序中上传多个文件时遇到问题。在这里,我试图在onSelectedFileMultiple($event) 中附加多个文件,但只有一个文件正在选择,如果我选择另一个文件,它将被新文件替换,但实际期望是它们需要相互附加并使用我需要的 post 方法传递所有被选中文件的 JSON 数据。
打字稿:
productForm: FormGroup;
public imagePath;
public files = [];
constructor(public productService: ProductService, private formBuilder: FormBuilder) { }
ngOnInit() {
this.productForm = this.formBuilder.group({
imagePath: ['']
})
}
public onSelectedFileMultiple(event) {
if (event.target.files.length > 0) {
for (let i = 0; i < event.target.files.length; i++) {
let file = event.target.files[i]
this.files.push(file)
this.productForm.get('imagePath').setValue(this.files[i]);
console.log(this.files)
}
}
}
public onProductSubmit(): any {
const formData = new FormData();
formData.append('imagePath', this.productForm.get('imagePath').value);
//checking value of imagePath after appending to formData
for (var pair of formData.entries()) {
console.log(pair[0] + ': ' + pair[1]); //returning value as imagePath: [object FileList]
}
this.httpClient.post('http://localhost:4000/api/v1' + '/post-product', formData);
HTML:
<form fxLayout="row wrap" [formGroup]="productForm" (ngSubmit)="onProductSubmit()" enctype="multipart/form-data">
<div fxFlex="100" fxFlex.gt-sm="100" class="px-1" ngClass.sm="mt-1" ngClass.xs="mt-1" method="post">
<label>Upload Image</label>
<mat-form-field class="w-100 form-group">
<ngx-mat-file-input multiple type="file" formControlName="imagePath" name="imagePath" placeholder="PDF file only" (change)="onSelectedFileMultiple($event)" [accept]="'application/x-zip-compressed,image/*'"></ngx-mat-file-input>
<mat-icon class="btn-project" mat-raised-button color="accent">folder</mat-icon>
</mat-form-field>
</div>
<div class="button-wrap" fxFlex="100" fxFlex.gt-sm="100" class="px-1" ngClass.sm="mt-1" ngClass.xs="mt-1">
<button class="btn-project" mat-raised-button color="accent" type="submit">Post Product</button>
</div>
</form>
预期的 JSON:
[{
"attachmentName": "file1.txt",
"attachedFile": "https://mean-ecom.s3.ap-south-1.amazonaws.com/1597294401122"
},
{
"attachmentName": "image2.jpg",
"attachedFile": "https://mean-ecom.s3.ap-south-1.amazonaws.com/1597294403496"
}]
【问题讨论】:
标签: javascript arrays angular typescript angular-file-upload