I am having problems trying to upload a photo from my frontend.
I have an input file where I can select a file from my computer.
What I want It is send that photo to my backend and store it as a Blob.
First I try to get the file and save as Blob:
foto: Blob;
setFoto(event){
this.foto = event.target.files[0];
}
But I don't know if this It is correct.
Second I send "this.foto" to the server using HTTP post and save in my db as blob. I think that my problem is that i am not sending the correct information about the photo.
In resume, what I want is send an image that I select from my computer to the server but I am having problems getting the correct information of the photo.
Solution founded
First, here is my input:
<input type="file" (change)="setFoto($event)">
Second, here is the method that you call when you select a photo.
setFoto(event) {
const foto = new Blob([event.target.files[0]]);
var reader = new FileReader();
reader.readAsDataURL(foto);
reader.onloadend = () => {
this.foto = reader.result;
}
}
this.foto is a string. Then when i click on update button i send the new photo as url and save it in my db (Mysql) as TEXT.
updateApuesta() {
this.userService.updateBet(this.url, {
id: this.userService.getIdbet(),
coste: this.coste,
beneficio: this.beneficio,
foto: this.foto
}).subscribe(this.success.bind(this), this.error);
}
When I try to get the photo from my server I use this. I call my http get service and get the photo.
First, the new image is a
image: SafeResourceUrl;
and I assign the dat that I got from my server.
this.image = this.sanitizer.bypassSecurityTrustResourceUrl(data.foto);
You have to import:
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
and pass it to your constructor:
constructor(private sanitizer:DomSanitizer ) { }
So finally, you got your image in this.image that is a SafeResourceUrl type. To load it in a you have to do this:
<img [src]="bet.foto"/>
where in your case bet.foto will be yout this.image that you have to pass to the template.