I am attempting to use FormData in order to upload a file through an HTTP Request. Here is the HTML code:
<ng-template #displayApp>
<div class="display flex justify-content-center">
<div >
<p-fileUpload
chooseLabel="Select First File"
[showUploadButton]="false"
[showCancelButton]="false"
(onSelect)="checkFilesSelected()"
(onRemove)="checkFilesSelected()"
#originalFile>
</p-fileUpload>
</div>
<div style="margin: 0 20px;"></div>
<div >
<p-fileUpload
chooseLabel="Select Second File"
[showUploadButton]="false"
[showCancelButton]="false"
(onSelect)="checkFilesSelected()"
(onRemove)="checkFilesSelected()"
#revisedFile>
</p-fileUpload>
</div>
</div>
<div style="margin-bottom: 20px;"> </div>
<div class="display flex justify-content-center">
<p-button [disabled]="!areFilesSelected" (click)="onUpload()">Compare Files</p-button>
</div>
</ng-template>
I am choosing two files and attempting to upload both files together with a single call to keep them synchronized.
Here is my component's TS file:
@ViewChild('firstFile') firstFile!: FileUpload;
@ViewChild('secondFile') secondFile!: FileUpload;
onUpload() {
console.log("File upload called",);
const originalFiles: File = this.originalFile.files[0]
const revisedFiles: File[] = this.revisedFile.files;
let formData: FormData = new FormData();
console.log("First ",originalFiles, originalFiles.name)
debugger;
formData.append('First', originalFiles)
console.log("Form Data ", formData)
let uploadUrl = new URL('baseURL');
uploadUrl.searchParams.append('First',"first");
uploadUrl.searchParams.append('Second',"second");
this.http.post(uploadUrl.toString(), formData).subscribe(
response => {
console.log('File uploaded successfully:', response);
},
error => {
console.error('Error uploading file:', error);
}
);
}
I have noticed that originalFiles
gets populated with file details. However, when I try to append it to formData
, it remains empty without throwing any exceptions. The formData appears empty when viewed on the console.
Any assistance on this issue would be greatly appreciated.
I attempted to change the data type to File instead of FileUpload, but it did not resolve the issue. Using event.Files[0] appends the file correctly. I am unsure how to merge this event into a single one for file uploads.