Getting pictures dynamically from the backend with unspecified file types

Greetings to my fellow Stackoverflow-Users,

Lately, I was tasked with the requirement of loading images dynamically from the backend into my application. Up until now, it was always assumed that we would only be dealing with SVG images since there was no clarification in the documentation or any other source. This assumption made things easier for me as I had a basic understanding of how to handle SVG images.

getGmaLogo(gmaId) {

this.httpClient.get(ApiUrls.QA_GMA_LOGO + "/" + gmaId, { headers: this.authHeader, responseType: "text" })
  .pipe(catchError(error => {
  // These error messages are tailored by me 
    this.errorService.showError(error);
    return this.errorService.handleError(error);
  }))
  .subscribe(image => {         

    let base64EncodedString = window.btoa(image)

    this.gmaLogo = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/svg+xml;base64,' + s);
  })

}

I then displayed the image on my page using the following code.

<img [src]="gmaService.gmaLogo || ''" alt="Company Name"/>

However, things are never as straightforward as they seem, are they?

It turns out that I may receive jpeg, png, and various other formats instead of just SVG. It seems inconvenient to restrict users to only SVG icons. This brings me to my question... Is there a way to dynamically determine the type of data received in the response without explicitly setting a specific response type in the headers? Simply leaving it blank doesn't work because the default response type is JSON.

Answer №1

For my project, the Blob response type is utilized on the client-side without concerning myself with the file type. The functionality performs as expected. Check it out here: https://stackblitz.com/edit/angular-yuy5km

Service

getGmaLogo(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, {headers: this.authHeader, responseType: 'blob' });
}

Component

To convert Blob into an image, I opted to utilize the FileReader for reading the contents.

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

Subsequently, the image is retrieved from the service.

getImageFromService() {
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
      }, error => {
        console.log(error);
      });
}

HTML

<img [src]="imageToShow" />

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

What is the best way to condense a repetitive method declaration and make it more concise?

I'm facing a situation where I have declared similar const values. Here's my current setup... import React from 'react' function Component_a() { const x = 5; const y = 10; const image_a = [...Array(x)].map((e, i) => ...

What's better in React: using pure components or non-pure components? Is it okay to fetch data in componentDidMount or

Exploring React in Meteor has led me to observe two distinct approaches... Take the meteor leaderboard example, where a list of players displays their names and scores. The pure approach involves fetching all players and passing them into the playersList ...

jQuery Mishap - Creating an Unspecified Issue

At the moment, my website displays a list of registered users in one column and their email addresses with checkboxes next to them in another column. Users can check the boxes and then click a submit button to generate a list of the selected emails separat ...

Ajax request in Rails not receiving a response from the controller

After troubleshooting a simple GET request to the controller action, I confirmed that the request is being made successfully and there are no issues with the controller executing the action. However, I am not receiving any response data. $.ajax({ url: ...

Require a v-alert notification to appear on every page, ensuring visibility across the site

Imagine a scenario where there is a right drawer that displays a grade dropdown with options like grade1, grade2, and grade3. On all pages, I need a v-alert notification strip to show the total count of students. For example, if I select grade3 from the ri ...

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...

Dynamically sending data to child components in Vue.js

I'm currently working on a progress bar implementation where the progress status is determined by the submitAction method. The value for the progress bar is constantly being updated in this method. Here's my code: 1. Parent Component <templa ...

Leverage the power of JSON data in conjunction with HighCharts through

I'm struggling to understand the JSON format and HighCharts. Despite trying various techniques found on forums, I haven't been able to achieve the desired result. Here's my issue: 1- When clicking, an Ajax call is made to a PHP file that g ...

How to integrate Three.js into Angular 14 while managing dependencies

I'm currently working on developing a web app using angular cli and incorporating three.js for enhanced product interaction. Despite watching numerous tutorials, I've been unable to successfully integrate three js into angular 14. It seems to wor ...

How can one click the button within the expanded dropdown while hovering over the navigation item in Angular and Bootstrap?

Issue Description: Upon hovering over a navigation item, the dropdown container is displayed but it's not clickable. Desired Behavior: Hovering over a navigation item should display the dropdown container and allow clicking on its contents. Furthermo ...

Displaying two different dates in AngularJS without any repetition of the similar elements

How can I elegantly display a date range that includes two dates, without repeating information if it's the same for both dates? My idea is something like this: Tue, 05 May 2015 19:31-20:31 GMT Mon, 04 19:31 - Tue, 05 20:31 May 2015 It's accept ...

In Javascript, where are declared classes stored?

When working in a browser environment like Firefox 60+, I've encountered an issue while attempting to retrieve a class from the global window object: class c{}; console.log(window.c); // undefined This is peculiar, as for any other declaration, it w ...

Having trouble retrieving the file using the MS Graph API, however, it is successfully accessible through Graph Explorer

User B received an excel file shared from User A's Onedrive, whether it is in the personal folder or business OneDrive. Accessing it through regular means such as a link works fine for user B. Running the call in MS Graph Explorer produces the expect ...

Resolving TypeScript Problem: Showing Error Alerts from React Hook Form

Currently, I am developing a registration form using react-hook-form within a React application. The form I'm working on includes validation for various fields, and my goal is to show error messages for each field. However, I have hit a bump in the ro ...

Is there a way for me to receive a success message when I successfully set data in Firebase?

I want to retrieve the orderId after successfully adding an order to the Realtime database using angularfirestore. What should I use after set() method to return the orderId? The structure of my order object is as follows: const orderObj: Order = { pay ...

My API is feeding data to the Material UI CardMedia image

Has anyone encountered a similar error while using the CardMedia API provided by Material-UI? I am currently utilizing the Card & CardMedia components from material-ui to display data fetched from an api. However, I am facing difficulty in displaying ...

The tooltip chart is not displaying all of its data

I create a dynamic tooltip with a custom chart inside of it. tooltip: { borderRadius: 15, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none', useHTML: true, shared: true, formatter: function() { ...

Guide to making a toggle button with a Light/Dark mode functionality

I have implemented a light/dark toggle button and now I want to integrate the functionality for switching between light and dark themes on my webpage. The switch should toggle the theme between dark and light modes when clicked. Some basic styling has been ...

Is it possible for me to include a static HTML/Javascript/jQuery file in WordPress?

My extensive HTML file contains Javascript, jQuery, c3.js, style.css, and normalize.css. I am wondering if I can include this file as a static HTML page within Wordpress. Say, for instance, the file is called calculator.html, and I want it to be accessib ...

Creating a JAR file for an Angular 2 application with Maven

My Front-End application is constructed using Angular2 + Webpack, organized as follows: > app > config > dist > dll > node_modules > src pom.xml package.json ... (other files) Currently, I am exploring th ...