2

I have a list of users called from a database using a spring boot API.

Each of these users has various attributes like username, id, first name, last name, registration date and profile photo which the id of an uploaded file(hosted in a sub-folder in the spring project main folder after the upload) in another database table called files.

To get an image you must a correct JWT token(which you get after signing in) and use the path: 'http://localhost:8082/downloadFile/' + imageid.

Under the users list mentioned above I've created a div which would be filled after clicking on one of the users with the selected user's attributes and show the actual user profile picture.

I found a stackoverflow post on how i could convert the image link to an actual photo so I followed the instructions.

The problem is after doing what was written in the answers I keep getting this error:

ERROR Error: 
"Uncaught (in promise): HttpErrorResponse: { 
    "headers": { 
        "normalizedNames:{},
        "lazyUpdate":null 
     },
     "status":403,
     "statusText":"OK",
     "url":"http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292",
     "ok":false,
     "name":"HttpErrorResponse",
     "message":"Http failure response for http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292: 403 OK", 
    "error":{}
}"

Here's my .ts component:

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
  this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
  this.service.getAllUsers(this.loginuser.token).subscribe(u => {
  this.dataSource.data = u as User[];
  console.log('datasource: ', this.dataSource.filteredData);
  this.users = u;
  console.log('user: ', this.users);
  });
 }

ngOnInit() {
}

onRowClicked(selectedItem) {
  console.log('selected item: ', selectedItem);
  document.getElementById('msg').style.display = 'none';
  document.getElementById('info').style.display = 'block';
  if (selectedItem.photoProfile === 'http://localhost:8082/static.images/user/default.jpg') {
  this.imgSrc = 'C:/Users/Adam/Documents/CODE/Ang/StarAdmin-Free-Angular-Admin-Template/src/assets/default.jpg';
} else if (selectedItem.photoProfile === 'null') {
  console.log('null');
} else {
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(currentUser.token);
  this.getFile('http://localhost:8082/downloadFile/' + selectedItem.photoProfile, currentUser.token);
}
}

getFile(url: string, token): any {
const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
this.http.get(url, {
  responseType: 'blob',
})
  .toPromise()
  .then((res: any) => {
    let blob = new Blob([res._body], {
      type: res.headers.get('Content-Type', headers)
    });

    let urlCreator = window.URL;
    this.imgSrc = this.sanitizer.bypassSecurityTrustUrl(
        urlCreator.createObjectURL(blob));
  });
}
}

export interface User {
id: number;
username: string;
firstName: string;
lastName: string;
email: string;
enabled: string;
registeredDate: Date;
}
ScieCode
  • 1,706
  • 14
  • 23
i'mgnome
  • 483
  • 1
  • 3
  • 17
  • For anyone who got the same problem as me, you might wanna check [this link](https://stackoverflow.com/questions/45530752/getting-image-from-api-in-angular-4-5) – i'mgnome May 27 '19 at 03:57

1 Answers1

0

it looks like you never pass in the headers object that you create right above the call to your GET request. Change your request to something like:

const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});

this.http.get(url, headers=headers, { responseType: 'blob', })

rmrouse88
  • 291
  • 1
  • 3
  • when i do that I get 'expected 1-2 arguments but got 3' – i'mgnome May 27 '19 at 02:57
  • you may have to roll your {responseType: 'blob'} handling into the options object. The get method expects two positional parameters: A url and an Options object. The Options object accepts multiple properties including headers. See [this](https://stackoverflow.com/questions/42352854/how-i-add-headers-to-http-get-or-http-post-in-typescript-and-angular-2?rq=1) post for an example of using the broader Options object. – rmrouse88 May 27 '19 at 03:04