In our Angular project we have a form containing form fields and PrimeNG FileUpload and we have tried to send form data with the selected files.
We have look at the documentation and lots of examples on the web, but none of them fulfill our requirements (sending form and files using Save button rather than auto upload or FileUpload button).
We tried the following approach by appending each model properties to the files in the file upload request but I think there must be a smarter way by appending files to the model properties in Save method (in .ts file).
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);
}
You may use onSelect event:
<p-fileUpload name="files" (onSelect)="dealWithFiles($event)"></p-fileUpload>
And in your component:
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
}
As you want to upload manually(by another button), then hide the default upload button by adding:
<p-fileUpload name="files" showUploadButton="false" (onSelect)="dealWithFiles($event)"></p-fileUpload>
Add a reference to your p-fileUpload
so that you can invoke upload
method on it from your Save method.
<p-fileUpload #fileInput name="files" ...
and
@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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With