I have used Image Cropper
in my Angular project for cropping images before uploading. Some parts of my code are:
component.ts
.
.
.
croppedImage: any = '';
.
.
.
imageCropped(event: ImageCroppedEvent) {
this.croppedImage = event.base64;
}
.
.
Base64ToFile(url: any, filename: any, mimeType: any){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename,{type:mimeType});})
);
}
OnSubmit() {
const filedata = new FormData();
this.Base64ToFile(this.croppedImage, "myphoto.png", "image/png").then(function(outputFile){
console.log(outputFile);
filedata.append("file", outputFile, outputFile.name);//The first parameter "file" is the input parameter in API method
});
this.http.post('https://localhost:5001/api/featuredpost/postimage/' this.selectedPostId, filedata).subscribe(
response => {
console.log(response);
}
);
}
API action:
public async Task<IActionResult> PostImage([FromForm] IFormFile file, [FromRoute] int id){
.
.
.
}
The problem is that when I debug my API, the input file
parameter is null while cropped image
has a base64
text value. How can I fix it?
CodePudding user response:
this.http.post
needs to be in a .then(...)
of the this.Base64ToFile(..)
call
You're not waiting for the async
fetch
to complete before the API post