Display an image in an Angular application using a secure URL

I am trying to return an image using a blob request in Angular and display it in the HTML.

I have implemented the following code:

<img [src]="ImageUrl"/>

This is the TypeScript code I am using:

private src$ = new BehaviorSubject(this.Url);
    dataUrl$ = this.src$.subscribe(url => {
        return this.imageService.GetImage(url, this.id).subscribe(data => {
            this.ImageUrl=data.changingThisBreaksApplicationSecurity;
            return data.changingThisBreaksApplicationSecurity
        })
    });

Here is my service implementation:

GetImage(url, id): Observable<any> {
    return this.httpClient
        .get(this.appConfig.apiEndpoint+ url + id, { responseType: 'blob' })
        .pipe(
            map(res => {
                if (res) {
                    return this.domSanitizer.bypassSecurityTrustUrl(URL.createObjectURL(res));
                }
                return null;
            })
        )
}

However, when I try to display the image in the HTML, it uses the following URL:

<img src="unsafe:blob:http://localhost:4200/6868babb-5ab2-491f-b519-2f2a3d0ed351">

But no image is displayed. What could be causing this issue? How can I resolve it?

Answer №1

I encountered a similar issue, but managed to solve it by implementing the following:

For HTML:

<img [src]="transform(imageURI)" />

In TypeScript:

transform(url) {
   return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
 }

Answer №2

Here's a solution that worked for me and hopefully will work for you as well:

Within my component:

import { OnInit, ElementRef } from '@angular/core';

export class myComponent implements OnInit {
@ViewChild('myImage', { static: false }) private myImage: ElementRef

   ngOnInit() {
   }

   getMyImage(url: string): void {
    this.service.getImage(url)
        .subscribe(response =>
            this.myImage.nativeElement.src = window.URL.createObjectURL(response)
        )
   }
}

Within my service:

getImage(url: string): Observable<Blob> {
    return this.http.get(`${environment.api}/file/download/` + url, {responseType: 'blob'})
}

Within my HTML:

 <img #myImage>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing a complex array structure in javascript into a CSV format

I have a complex nested array that I need to convert into a downloadable CSV file. My current approach involves iterating through each array and subarray to build the CSV, but I'm wondering if there's a more efficient method available? Here is a ...

Nesting two ngFor loops in Angular using the async pipe leads to consistent reloading of data

In my Angular application, I am trying to retrieve a list of parent elements and then for each parent, fetch its corresponding children (1 parent to n children). Parent Child1 Child2 Parent Child1 Parent3 Child1 Child2 Child3 Initially, I succes ...

Button appears and disappears sporadically while browsing in Safari

I created a slider using SCSS, JavaScript, and HTML. You can view the demo at this link: https://jsfiddle.net/rr7g6a1b/ let mySlider = { initializeSlider: function (options) { let slider = options.container; let slides = slider.querySelectorAll( ...

What is the optimal method for generating numerous records across various tables using a single API request in a sequelize-node.js-postgres environment?

I need to efficiently store data across multiple separate tables in Postgres within a single API call. While I can make individual calls for each table, I am seeking advice on the best way to handle this. Any tips or suggestions would be greatly appreciate ...

Recognizing when a Bootstrap dropdown with multiple options is deselected through Jquery

I'm working with a dynamic bootstrap multiple drop-down selector and I need to execute some code when a user deselects an option. <select id="selectOptions" multiple> <option>Test1</option> <option>Test2</option> & ...

Angular UI Router allows for the resolution of data before a state

When working on my angular sample route, I attempted to achieve the following: (function(angular){ 'use strict'; angular .module('appRouter',['ui.router']) .controller('routerCtrl',function( ...

combining input fields for editing as a single unit instead of individually

Current Situation : At the moment, I have a form where individual records of input fields such as firstName, lastName, and email can be edited and saved without any errors. Requirement : However, I now want to be able to edit and save the firstName and ...

Oops! The program encountered an error where it cannot assign a value to the 'id' property of an undefined object while trying to store a session in redis

I am currently working on an Angular4 login application and I am looking to store sessions in Redis. To accomplish this, I am utilizing Express session. However, I have encountered the following error: req.session.id = userName; ...

The Issue of Double-Clicking on Table Cells in Internet Explorer 8

I implemented a JQuery function to add a double click event listener to a table, which triggers a modal popup when a cell is double-clicked. While this functionality works seamlessly in Firefox, there is an issue in IE8 where double-clicking a cell highli ...

execute a function once an asynchronous function has finished running

I have observed the practice of calling functions in succession using promises, and I have an async function with observables. fetchData() { this.generatePayload() this.dataService .getData(this.payload) .subscribe( (data: any ...

Using ReactJS and JavaScript to transform an array into a fresh array

I am working with an array that looks like this: var oldArray = [ {number: '12345', alphabet: 'abcde'}, {number: '54321', alphabet: 'abcde'}, {number: '67891', alphabet: 'abcde'}, ...

Supply additional parameters to the method decorator within an Angular component

Imagine a scenario where there are multiple methods requiring the addition of a confirmation dialog. In order to streamline this process, a custom decorator is created. @Component({...}) export class HeroComponent { constructor(private dialog: MatDialog ...

Different ways to use jquery to move to the top of an overflow div

$('.lb').click(function() { $('#modal').hide(); var id = $(this).attr('id'); var dir = '/lightbox/' + id + '.php'; $('#lightbox').find('#modal').load(dir, function() { ...

JavaScript does not recognize jsPDF

After importing the jsPDF library, I attempted to export to PDF but encountered a JavaScript error stating that jsPDF is not defined. I tried various solutions from similar posts but none of them seemed to work for me. You can find the fiddle here: https ...

Remove option from MUI Autocomplete after it has been selected

I am currently utilizing a Material-UI Autocomplete component. To avoid users selecting the same element twice, resulting in duplicate ID numbers, I want to remove the element from the dropdown entirely. For instance, if "Shawshank Redemption" is selected ...

Pattern without anything to duplicate

Could someone help me figure out what I'm doing wrong with this regular expression? I need to create a regex that matches phone numbers in three specific formats: "+38 (093) 937-99-92", "093 937 99 92", and "(093) 937 99 92". As I started working on ...

Incapable of acquiring the classification of the attribute belonging to the

Is it possible to retrieve the type of an object property if that object is stored in a table? const records = [{ prop1: 123, prop2: "fgdgfdg", }, { prop1: 6563, prop2: "dfhvcfgj", }] const getPropertyValues = <ROW extends o ...

What steps should I take to include a Follow - Unfollow Button on my Website?

I need to add a button on my website that allows users to either follow or unfollow a specific game. Here is the table for the follow buttons: Follow Button Table When a user clicks on the button related to the game ID, it should update the game_follow d ...

Triggering blur event manually in Ionic 3

Is there a way to manually trigger the blur event on an ion-input element? The ideal scenario would be with an ionic-native method, but any javascript-based workaround will suffice. My current configuration: Ionic: ionic (Ionic CLI) : 4.0.1 (/User ...

"Data is not defined" error message is triggered when using jQuery DataTable Row Details

While utilizing jQuery Data Tables to construct a datatable with row details, I encountered an error in jquerydatatables.js: data is undefined The JavaScript code being used is: $(document).ready(function() { var dt = $('#tbl_cheque_history' ...