I am building a form in angular which is used to upload a file and I have a third party API that I need to call which accepts Multi part form data and file as blob. Can you please tell me how can I do that? I have this code for now?
HTML
<form [formGroup]="customerFileGroup" (submit)="submit($event)">
<div>
<input
formControlName="file"
type="file"
accept=".csv,text/plain, text/csv, text/html"
(onSelection)="changeFile($event)"
/>
</div>
<button>Submit</button
</form>
Typescript
export class CustomerFile{
constructor(private readonly _fb: FormBuilder) {}
const customerFileGroup: FormGroup = this._fb.group({
file: this._fb.control(null),
});
submit(e: Event): void {
e.preventDefault();
const formData = new FormData();
formData.append('file', this.fileUploadGroup.value);
// this.customerFileService.uploadFile(formData.file?);
What should I send here because the API requires file as blob now
}
File/API
public uploadFile(
file: Blob
)
{
// Black box for me
}
Swagger
I am trying to understand what do I need to pass in the service so it is multi part form data but the request body of file is a blob. I am using Angular 10. Let me know if more info is required
If I pass the formdata, I get the following error:
Argument of type 'FormData' is not assignable to parameter of type 'Blob'
You shouldn't use ngModel
or formControl
to get file, you have to store the file in variable manually when file changes, see the example below
<form [formGroup]="customerFileGroup" (submit)="submit($event)">
<div>
<input
formControlName="file"
type="file"
accept=".csv,text/plain, text/csv, text/html"
(change)="changeFile($event)" <!-- Change event name to "change" -->
/>
</div>
<button>Submit</button>
</form>
export class CustomerFile{
...
fileToUpload: FileList;
changeFile(evt) {
this.fileToUpload = evt.target.files[0];
}
submit(e: Event): void {
e.preventDefault();
const formData = new FormData();
formData.append('file', this.fileToUpload);
this.customerFileService.uploadFile(formData);
}
}
export class CustomerFileService {
...
public uploadFile(payload: FormData) {
return this.http.post('<API_URL>',payload);
}
}