[英]File Upload in Angular catching value but not posting data
幾天來,我一直在嘗試使用 ngx-material-file-input 在我的 Angular 應用程序中上傳多個文件。 我正在使用 angular 反應式 forms,在控制台中記錄數據時沒有錯誤。 鍵imagePath
在將 imagePath 附加到它之后安慰formData
時獲得一個值[object FileList]
。 但由於某種原因,數據庫中實際上沒有發布任何內容。 在下面查看我的代碼以獲取更多詳細信息。 任何形式的幫助表示贊賞。
更新::如果單個文件上傳完成並使用下面的onSelectedFile($event)
但仍然無法上傳多個文件,則它正在工作
onSelectedFile(event) {
const file = event.target.files[0];
this.productForm.get('imagePath').setValue(file)
console.log(file)
}
typescript:
productForm: FormGroup;
public imagePath;
constructor(public productService: ProductService, private formBuilder: FormBuilder) { }
ngOnInit() {
this.productForm = this.formBuilder.group({
imagePath: ['']
})
}
public onSelectedFileMultiple(event) {
if (event.target.files.length > 0) {
const files = event.target.files;
this.productForm.get('imagePath').setValue(files);
console.log(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>
問題出在onSelectedFileMultiple($event)
上,它只將 imagePath 的單個值附加到 formData。 可以做的只是遍歷文件數組和 append 該數組中的每個文件到 formData
public onProductSubmit(): any {
const formData = new FormData();
files.forEach(file => {
formData.append('imagePath[]', file);
})
this.httpClient.post('http://localhost:4000/api/v1' + '/post-product', formData);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.