angular - PrimeNG - 透過按鈕點擊傳送表單資料和檔案上傳資料
在我們的 Angular 專案中,我們有一個包含表單欄位和 PrimeNG FileUpload 的表單,我們已經嘗試過將表單資料與選擇的檔案一起傳送。
我們已經查看了文件和網路上的許多範例,但沒有一個符合我們的需求(使用儲存按鈕傳送表單和檔案,而不是自動上傳或使用檔案上傳按鈕)。
我們嘗試了以下方法,透過將每個模型屬性附加到檔案上傳請求中的檔案,但我認為一定有更聰明的方法,可以在 Save 方法(在 .ts 檔案中)中將檔案附加到模型屬性。
Html:
<p-fileUpload name="files" url="/MyController/Save"
(onBeforeSend)="onBeforeSendFile($event)"
(onUpload)="onUploadFile($event)"
(onError)="onErrorFile($event)"
(onBeforeUpload)="onBeforeUploadFoto($event)"
multiple="multiple"
chooseLabel="Select"
uploadLabel="Load"
cancelLabel="Cancel">
</p-fileUpload>
.ts:
//code omitted fo brevity
//at here we append model properties to the array in file upload request:
onBeforeUploadFoto(event: any) {
event.formData.append('id', this.entityId);
event.formData.append('name', this.entityName);
}
答案#1
你可以使用 onSelect 事件:
<p-fileUpload name="files" (onSelect)="dealWithFiles($event)"></p-fileUpload>
在你的組件中:
dealWithFiles(event) {
files = event.originalEvent.files;
// Deal with your files
// e.g assign it to a variable, and on submit add the variable to your form data
}
如果你想手動上傳(通過另一個按鈕),那麼可以通過添加以下內容來隱藏默認的上傳按鈕:
<p-fileUpload name="files" showUploadButton="false" (onSelect)="dealWithFiles($event)"></p-fileUpload>
答案#2
在您的 p-fileUpload 中添加一個引用,這樣您就可以在您的 Save 方法中調用它的 upload 方法。
<p-fileUpload #fileInput name="files" ...
和
@ViewChild('fileInput') fileInput: FileUpload;
// ...
// save method manually called by clicking on your Save button
save() {
if (this.fileInput && this.fileInput.files.length > 0) {
this.fileInput.upload();
}
}
