1

I am trying to store image in mongodb and display it back to Angular. I am done with upload, but I am getting error while I try to display. I tested my API in POSTMAN. It is working fine. I think the error is because of the response type.

API

    get('/images',(req, res, next) => {
      const user = AuthBase.getUser(req, res);
      this.model.findOne({\[this.userForeignKey\]: new mongoose.Types.ObjectId(user._id)}, (err, image) => {
          if (err) {
              res.sendStatus(400);
          }
          // stream the image back by loading the file
          res.setHeader('Content-Type', 'image/jpeg'); 
          fs.createReadStream(path.join(UPLOAD_PATH, image.filename)).pipe(res);
//if I add res.json(image) here, I am not getting any error but the Image is getting broken        
 })
    });][1] 

Service

getImage(): Observable<any> {
  return this.http.get(`/api/images`);
}

Component

images:[]
  getImage() 
  {
 this.patientService.getImage().subscribe(
    data =>{ 
   this.images = [data]; 
   console.log(data); },
    error => console.log(error) ); 
  }
Sidhu Tesingu
  • 85
  • 2
  • 13
  • 1
    Something is assuming your response is JSON,, and not an image. Is this an angular thing? – Evert Jul 07 '18 at 07:13
  • what is output in console.log() data of subscribe – Krishna Rathore Jul 07 '18 at 07:13
  • 1
    HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:4200/api/images", ok: false, …} error : {error: SyntaxError: Unexpected token � in JSON at position 0 at Object.parse () at XMLHt…, text: "����C↵ ↵↵ …+�9�ڷ�"�q����X�{�?߄�Silֹ�k��ƶ�����؎1�m/��"} headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message : "Http failure during parsing for http://localhost:4200/api/images" name : "HttpErrorResponse" ok : false status : 200 statusText – Sidhu Tesingu Jul 07 '18 at 07:16
  • 1
    What's the point of your getImage() service in the first place? To display an image in your template, you need to put the **url** of the image in the src property, and the browser will load the image. So loading the image using a AJAX request isn't needed. – JB Nizet Jul 07 '18 at 07:19
  • Cinque Terre I am doing this – Sidhu Tesingu Jul 07 '18 at 07:20
  • 1
    But your REST service doesn't return a JSON object (img) with a url property. It returns the bytes of the JPEG image. All you need is ``: the browser will then load the bytes of the image returned by your REST service by making a request to /api/images. – JB Nizet Jul 07 '18 at 07:25
  • I am using JWT token for authorization and session. So If i use `` It is showing 401 **unauthorized** – Sidhu Tesingu Jul 07 '18 at 07:38

1 Answers1

2

Include the response type with get request

getImage(): Observable<any> {
  return this.http.get(`/api/images`,{ responseType: 'blob' });
}
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • `Blob(23413) {size: 23413, type: "image/jpeg"} size:23413 type:image/jpeg" proto__:Blob` I am getting this in console. Unexpected token in JSON error is gone now. But I am not able to display image – Sidhu Tesingu Jul 07 '18 at 07:46
  • 1
    you need to convert your blob to image format check this for convert blob to image https://stackoverflow.com/questions/45530752/getting-image-from-api-in-angular-4 – Chellappan வ Jul 07 '18 at 07:49