How to use image blob in Angular JS?

Working with API endpoints that require authentication for image retrieval. Utilizing a service called authenticatedHttp as an abstraction over $http to manage authentication tokens successfully.

Successfully receiving response, converting blob to object URL. Validation confirmed on correct blob output.

Encountering issue when trying to apply objectUrl to src. Attempted simplified example without authentication in Angular app, works in vanilla JS.

Not well-versed in ObjectUrl, noticing that inspecting empty image shows correct src, clicking link redirects through ui-router.

Seeking insights on why this is happening and how to resolve it?

app.directive('authenticatedSrc', ['authenticatedHttp', function (authenticatedHttp) {
  var directive = {
      link: link,
      restrict: 'A'
  };
  return directive;
  function link(scope, element, attrs) {
    var requestConfig = {
      cache: 'false'
    };
    authenticatedHttp.get(attrs.authenticatedSrc, requestConfig).then(function(response) {
      var objectUrl = window.URL.createObjectURL(new Blob([response.data], { type: 'image/png' }));
      attrs.$set('src', objectUrl);
    });
  }
}]);

Answer №1

When downloading binary data, it's crucial to specify the responseType:

app.directive('customSrc', ['customHttp', function (customHttp) {
  var directive = {
      link: customLink,
      restrict: 'A'
  };
  return directive;
  function customLink(scope, element, attrs) {
    var requestSettings = {
      //IMPORTANT
      responseType: 'blob',
      cache: 'false'
    };
    customHttp.get(attrs.customSrc, requestSettings).then(function(response) {
      //var objectUrl = window.URL.createObjectURL(new Blob([response.data], { type: 'image/png' }));
      var blobData = response.data;
      attrs.$set('src', blobData);
    });
  }
}]);

Otherwise, there is a risk of data corruption due to conversion from UTF-8 to DOMstring (UTF-16).

To learn more, refer to MDN XHR API ResponseType.

Answer №2

@Kaiido's input was noted but did not directly address my main issue.

Although @georgeawg provided a solution to most of my problem, I chose not to accept it due to the fact that his method (using the blob as the source) did not yield successful results for me.

After some adjustments, here is the final version of the code that effectively resolved the issue:

app.directive('authenticatedSrc', ['authenticatedHttp', function (authenticatedHttp) {
  var directive = {
      link: link,
      restrict: 'A'
  };
  return directive;
  function link(scope, element, attrs) {
    var requestConfig = {
      cache: 'false',
      responseType: 'blob'
    };
    authenticatedHttp.get(attrs.authenticatedSrc, requestConfig).then(function(response) {
      var reader = new window.FileReader();
      reader.readAsDataURL(response.data);
      reader.onloadend = function() {
        attrs.$set('src', reader.result);
      };
    });
  }
}]);

Answer №3

What type of data does response.data return? Is it a base64 encoded string? Using the img tag, base64 encoded images can be rendered by providing directly in the src attribute. You can also utilize the $sce service in angularjs to ensure that the objectUrl is trusted as a valid URL. Use $sce.trustAsURL(objectUrl) when adding it to the src attribute. For more information, visit https://docs.angularjs.org/api/ng/service/$sce

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

Troubleshooting $on in Angular

I have a situation where I need to pass a value from the Main controller to the Child controller. These are the two controllers involved: .controller('mainController', ['$scope', '$rootScope', '$location', 'CI ...

Creating a button in ReactJS with text displayed under an icon

Presently, I am working with a component that looks like this: https://i.stack.imgur.com/qGCwj.png This is the code for the component: import React from "react"; import {withStyles} from "material-ui/styles"; import Settings from "material-ui-icons/Setti ...

Transferring information through AJAX to the current page using a foreach loop in Laravel 5

As a newcomer to ajax and laravel 5, I am eager to learn how to pass data with ajax to populate a foreach loop in laravel 5 on the same page. <div class="row" style="margin:3% 0px 0px 0px"> @foreach($warung_has_kategoriwarungs['i want pass ...

Determining the width of a window using JavaScript

My website is experiencing some mysterious issues with $(window).width(). When I open my site in the Chrome Device Toolbar with a window size of 320xXXX, then run $(window).width() in Google Chrome's JavaScript console, it returns 980. As a result, n ...

Adjust the jQuery and PHP script to retrieve both the ID and text content to populate an OPTION element

I have a basic DROPDOWN list: <select class='form-control' id='builders' name='builder_id'> <option value="1">Java</option> <option value="2">Python</option> </select> I am looking ...

Retrieve information from a PHP file using AJAX when the output is just a single line

I never thought I would find myself in this situation, but here I am, stuck. I just need a single result from this PHP file, so is using an array really necessary? Despite my efforts to console.log(result) multiple times, all I get back is "null". What c ...

Obtain the range of values for a match from an array using Vue.js

I have an array in my Vue.js code with values 25, 100, 250, and 500. I am looking to find the key value that matches a specific range. For example, if the input is 5, then the output should be 25. However, the code I tried returns all values within the ran ...

Ways to stop click propagation in the case of a parent anchor link containing a button among its children

Every time I click on the Link parent, it triggers a click event on the button as well. I want these events to be independent. <Link className="product-item__link" to={`/products/${product.category}/${product.id}`} > <div className ...

A guide on extracting keywords from the tynt API using JavaScript

Looking to extract the inbound keyword from an API: What would be the best way to use JavaScript to extract and display the value of the inbound keyword from this API? ...

How can I fix the 'Null is not an object' error that occurs while trying to assess the RNRandomBytes.seed function?

Currently, I am in the process of creating a mobile application using expo and react-native. One of the features I am working on involves generating a passphrase for users on a specific screen. To achieve this task, I have integrated the react-native-bip39 ...

Update the page by selecting the refresh option from the drop-down menu

In my script, I have different views showing information retrieved from a database. One view displays the quantity of a product sold each month, another shows sales, the third presents profits, and the last exhibits calculated percentages using sales and p ...

Error encountered: The use of 'import' and 'export' is limited to 'sourceType: module' when attempting to install Tweakpane

I am currently learning JavaScript and have been following a course on Domestika that requires me to install the Tweakpane package. I usually use Git Bash for installing packages, and I have successfully installed others this way before. Here is the proces ...

Tips on handling parameters in the form of a single value or an array of values

I've implemented multiple functions structured like this: this.something = function (which) { // Can be one or many. if (!Array.isArray(which)) { // Single input case. doSomething(which); } else { ...

Material UI Appbar is throwing an error with an invalid hook call

For my project, I needed to create a simple app bar, so I decided to use the code provided on the Material UI website. Here is the component's code that I used: import React from 'react'; import { fade, makeStyles } from '@material-ui/c ...

Unveiling the power of Axios and Vue in fetching API data: The quest for

I've encountered a problem while trying to integrate my API with Vue/Axios. The issue arises when I attempt to store the data retrieved by Axios into an empty variable within the data object of my component. It throws an "undefined at eval" error. Can ...

Develop a monitor for an entity that has not been created

Currently, I am tackling a feature that involves tracking an asynchronous request within a synchronous one. Let me elaborate. The code snippet I am working with looks something like this: const myObj = {}; function sendMessage(requestId, data) { kafkaP ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

Preventing blank text entries in a task management application

Is there a way to determine if the text input provided by the user is empty or contains some text? I'm in the process of developing a TO-DO app and I'd like it so that if a user fails to enter anything into the text area and clicks on "add", the ...

Struggling to retrieve the tagName attribute when clicking in JavaScript

I am trying to extract the tagName of any element within an iframe when it is clicked. Unfortunately, my JavaScript code is not working as expected. As a beginner in JavaScript, I would appreciate some guidance on where I might be going wrong. <div cl ...

Is there a discrepancy in the value between data and computed properties in Vue components?

Upon reviewing my code, I have noticed that the value shown in the data of the component does not match the desired value. The code snippet is provided below: View.component('xxx-item',{ props:['item'], template:`xxxx`, computed: ...