简体   繁体   中英

How to send Blob image to NodeJs using Angular2?

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.

this.userService.updateBet(
this.url,{foto:this.foto}).subscr‌​ibe(this.success.bin‌​d(this), this.error); 

and the service is:

 updateBet(url, body) {
    return this.httpRequest.put(url, body, this.options);
  }

  put(url, body, options) {
    return this.http.put(url, body, this.setOptions(options))
      .map(this.extractData)
      .catch((error: any) => Observable.throw(error.json().error || 'Server error')); //Show errors if any
  }

But what i said, i think i am not sending the correct info about the photo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM