themyth92 / ngx-lightbox

Lightbox2 use with angular >= 5
MIT License
115 stars 70 forks source link

Display an image whose url requires authentication #112

Open hmsuchier opened 3 years ago

hmsuchier commented 3 years ago

Hi, Is there a way to display images whose url requires authentication ? In a normal context I use a pipe to catch query and attach authentication token, but is there a way to do such thing with the current lib ? Thanks !

themyth92 commented 2 years ago

Short anwser, NO. I would suggest u can attach the auth token in the image url and let your server to return the image if the auth is correct

oneplugin commented 1 year ago

Use this component

@Component({ selector: 'app-secured-image', template: <img [src]="dataUrl$|async"/> }) export class SecuredImageComponent implements OnInit { @Input() private attachment: Attachment = {};

private src$ = new BehaviorSubject(this.attachment); private url :Observable = undefined

constructor(private httpClient: HttpClient, private domSanitizer: DomSanitizer) {}

ngOnInit(): void {}

ngOnChanges(): void { this.src$.next(this.attachment); }

dataUrl$ = this.src$.pipe(switchMap(attachment => this.loadImage(attachment)))

private loadImage(attachment: Attachment): Observable { let params = {"id":attachment.id,"fileName":attachment.fileName,"objectPath":attachment.storagePath,"bucketName":"unknot"} const httpOptions : Object = { headers: new HttpHeaders({'Accept':'image/png'}), responseType: 'blob' }; this.url = this.httpClient.post(${environment.serverUrl}/file/download,JSON.stringify(params),httpOptions) .pipe(map(e => this.domSanitizer.bypassSecurityTrustUrl(URL.createObjectURL(e)) as string))

return this.url

} }

@ViewChildren('albumImages',{read: ElementRef}) albumImages!: QueryList

open handler open(index){ const albumImages = []; if( this.albumImages.length > 0 ){ for( const albumImage of this.albumImages){ const img = albumImage.nativeElement.querySelector("img") if( img && img.src != undefined){ const santizedUrl = this.domSanitizer.bypassSecurityTrustUrl(img.src) albumImages.push({ src: santizedUrl, caption: "", thumb: santizedUrl }) } this.lightbox.open(albumImages, index,{showImageNumberLabel:true,centerVertically:true,wrapAround:true,disableScrolling:true}); } } }

Works like charm