When i'm posting binary data for images from angular 14 to Asp.Net 6 Rest Api, i just find image path & it's name like that "C:\fakepath\2.jfif" but i lose binary data,How i can solve that problem. That's the service method by which i'm posting data to asp.net rest api
postAdvertisement(adv: Advertisement): Observable<Advertisement> {
return this.http.post<Advertisement>(this.baseApiUrl + '/api/advertisements',adv);
}
Component
export class PostAdvComponent implements OnInit {
advForm: FormGroup;
@Input() adv: Advertisement;
constructor(private fb: FormBuilder, private advService: AdvService) { }
ngOnInit(): void {
this.advForm = this.fb.group({
id: [0],
name: ['', Validators.required, Validators.minLength(1), Validators.maxLength(50)],
price: ['', Validators.required],
description: ['', Validators.required],
images: this.fb.array([
this.addImages()
])
});
}
addImages(): FormGroup {
return this.fb.group({
id: [0],
contents: ['', Validators.required]
})
}
uploadImage(event: any) {
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const file = files[i];
const reader = new FileReader();
reader.readAsBinaryString(file);
//reader.readAsDataURL(file);
reader.onload = (event) => {
const uint8Array = new Uint8Array(event.target?.result as ArrayBuffer);
const base64String = Uint8Array.from(uint8Array).toString();
//const jsonString = JSON.stringify({ data: base64String });
this.advForm.patchValue({
contents: base64String
})
}
}
addAdvertisement() {
this.mapFormValuesToAdvModel();
this.advService.postAdv(this.adv)
.subscribe(add => {
console.log(add);
});
}
mapFormValuesToAdvModel() {
this.adv.name = this.advForm.value.name;
this.adv.price = this.advForm.value.price;
this.adv.description = this.advForm.value.description;
this.adv.images = this.advForm.value.images;
}
}
Html
<div formArrayName="images">
<div formGroupName="0">
<div class="form-group" [ngClass]="{'has-error' : formErrors.images}">
<div class="input-group">
<input type="file" id="photo" (change)="uploadImage($event)" formControlName="contents" name="photo"
class="form-control-file" (blur)="logValidationErrors()" multiple="multiple" />
</div>
<span class="help-block" *ngIf="formErrors.images">
{{formErrors.images}}
</span>
</div>
</div>
</div>
I'm expecting to get binary data into controller's model but i can't get it