Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeNG - Sending form data and FileUpload data via button click

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);
}
like image 672
Jack Avatar asked Aug 29 '18 09:08

Jack


2 Answers

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>
like image 173
RzoQe Avatar answered Oct 30 '22 15:10

RzoQe


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();
    }
}
like image 1
Antikhippe Avatar answered Oct 30 '22 17:10

Antikhippe