I have a simple Angular component that retrieves a file from an input and sends it to the backend, along with other variables, using FormData.
// uploader.component.html
...other HTML elements
<div class="file-uploader-container">
<input (change)="handleFileUpload($event.target.files)" type="file" name="files" #fileField hidden/>
</div>
So, I listen to the change event of the element, create my FormData by appending the necessary data, and call the storage service.
// uploader.component.ts
handleFileUpload(files: FileList) {
try {
this.file = files.item(0) ?? undefined;
this.filename = this.file?.name;
if(!this.file) {
throw new Error('Error during the file upload')
}
if(this.allowedTypes.length && !this.allowedTypes.includes(this.fileType!)) {
throw new Error(`Invalid file format`)
}
const form = new FormData();
form.append('file', this.file); // <-- Causes other variables to be undefined when appended first
form.append('app_id', environment.app_id);
this.isUploading = true;
// * upload file on storage
...API CALL TO STORAGE SERVICE
} catch(error: any) {
this.swalService.showErrorMesssage(error.message);
this.clearInput();
}
}
I noticed that when I append the file first, the other variables that are appended become undefined when I retrieve them on the backend. However, this does not happen when I append the file at the end of the FormData. Why does this happen?