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

Methods for validating ajax response with Jasmine

I'm a newbie when it comes to jasmine and I'm trying to figure out how to verify if a specific node is present in the ajax response. Currently, I'm using grunt to run jasmine from the command line and have successfully tested if a function i ...

Encountering an issue in Angular 8 where a class is not being added after the page loads, resulting in an

Looking to dynamically add a class to a div element using Angular? I have a condition isTrue, and am utilizing the angular function ngAfterViewInit() to add the class hideOnLoad after the page loads when isTrue becomes true. Instead of traditional javascri ...

Check for pattern using JavaScript regular expression

Utilizing ng-pattern to validate a regular expression. The pattern must include 3 letters and 2 numbers in a group. For example: G-31SSD or G-EEE43 Currently, the pattern only matches the second example. ng-model="newGroup.groupCode" ng-pattern="/^&bso ...

Tips for concealing a "PARTICULAR TAB BAR ITEM" on a bottom tab bar in @react-navigation/bottom-tabs

Check out this video displaying my current visible bottom tab items: Home, My Account, Cart, and Menu. Watch here I have additional bottom tab items like SettingsView that I want to render on the screen but keep them hidden from the bottom tab bar itself. ...

The Vue route parameters are not recognized within the function type

Seeking assistance on extracting parameters from my route in a vue page, I have the following implementation: <script lang="ts"> import { defineComponent } from 'vue'; import { useRoute } from 'vue-router'; export ...

Javascript - Issue: Route.post() is in need of a callback function, however it received an [object Promise] instead

I'm encountering an issue with one of my express routes. The error message I am receiving is as follows: Error: Route.post() requires a callback function but got a [object Promise] This error seems to be related to the last line in controllerFunction ...

Unleashing the Power of Node.js: A Step-by-Step Guide to Crafting

I am developing a console interface that prompts the user with questions and receives input through the console. Some questions require the user to provide a limited number of inputs. I have researched ways to obtain console input in node js, but I haven&a ...

Divide a list Observable into two parts

In my code, I have an Observable called 'allItems$' which fetches an array of Items. The Items[] array looks something like this: [false, false, true, false] My goal is to split the 'allItems$' Observable into two separate Observables ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Tips for effectively parsing extensive nested JSON structures?

JSON Data on PasteBin I need assistance in converting this JSON data into an Object. It seems valid according to jsonlint, but I'm encountering issues with parsing it. Any help would be greatly appreciated. "Data":[{...},{...},] // structured like t ...

Limit access to Google Fusion Table to specific types of maps. Eliminate Google Fusion Table for selected map formats

Currently, I am in the process of creating a web map using the Google Maps Javascript API. My objective is to display a Google Fusion Table containing buildings in Boston exclusively on a stylized map named "Buildings." When I switch to the Buildings map t ...

Ensure that the form is validated even when setState is not executed immediately

I am currently working on a form in React and I am facing an issue with validation. When the Submit Form button is clicked without filling in the input fields, an error should be displayed. This part is functioning correctly. However, even when the fields ...

What causes the discrepancy between the response.headers in Angular and the response headers shown in the browser's developer

this.http.post(this.url+"/login",formData).subscribe( (response: any)=>{ console.log(response.headers); const cookies = response.headers.get('Set-Cookie'); // console.log(response.headers); console.log(c ...

What is the maximum string length allowed for the parameter accepted by JavaScript's JSON.Parse() function?

Is there a maximum string length limit for the parameter accepted by JavaScript's JSON.Parse()? If I were to pass a string that surpasses this expected length, will it result in an exception being thrown or prevent the function from returning a valid ...

Tips for modifying date format in Angular 8

My datepicker for a date column is displaying the incorrect date format after submission. I am looking to change this format to the correct one. I am working with bsConfig bootstrap in Angular 8, but I am unsure of how to modify the date format. The back ...

What is the process of converting the Object type returned from an Observable to an array of objects in Angular?

When utilizing the GET method to retrieve information, I have encountered a problem. Here is the code snippet: constructor(private http: HttpClient) { } items: Item[]; stuff: any[]; ngOnInit() { const url = ...; this.http.get(url) .subscribe(nex ...

What methods can I use to adjust my HTML content once I have parsed my JSON file?

<script type="text/javascript"> window.alert = function(){}; var defaultCSS = document.getElementById('bootstrap-css'); function changeCSS(css){ if(css) $('head > link').filter(':first').replaceWit ...

Is Kendo Telerik grid capable of applying conditional formatting while filtering?

Is it feasible to modify the background color of rows in a Kendo Telerik grid when a filter is implemented within an ASP.NET MVC application? ...

Using more than one submit button in an HTML form

I am attempting to include multiple buttons on a single form. I would like to perform different actions on the form depending on which submit button is clicked. <script type="text/javascript> $("#<portlet:namespace/>Form").submit(function( ...