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

Exploring the world of cookie security with SameSite and Secure features in ExpressJS

Despite having the specified settings on my express application, a warning keeps appearing in the console. Has anyone encountered this error before? I found some information related to it here: https://github.com/expressjs/express/issues/3095 The version ...

Angular.js: A revolutionary universal controller with customizable parameters and unique isolated scope feature

Picture a scenario where we have a product list comprising 3 categories: books, fruits, and electronics. Our goal is to retrieve 10 products from each category and exhibit them individually. Additionally, we aim for the flexibility of isolating each catego ...

What is the best way to ensure email address validation is done perfectly every time?

Can someone assist me with validating email addresses correctly? I am able to handle empty fields, but now I need a way to identify and display an error message for invalid email addresses. How can I modify my validation process to check for improper email ...

Unveil Information with Underscore JS

I am attempting to showcase my data in a table using Underscore.js. Below is the div container class I am working with: <div id="container"></div> Upon window load, I have added an event listener: window.addEventListener("load", function(ev ...

Learn how to automatically set the checked state of a radio button by toggling another radio button

I have two sets of radio buttons, each with four options. The first set has no default selection (unchecked) using jQuery, while the second set has the first option checked by default. What I'm looking to achieve is that when a radio button in the f ...

Applying a variety of class names in real-time based on JSON data results

Extracting multiple class names from a single key value in a JSON response and dynamically binding these class names. Here is an example of my JSON result: [ { "categoryId": 1, "categoryValue": "Mobiles", "divId": "MobilesId", "uiClass": ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

How to simultaneously update two state array objects in React

Below are the elements in the state array: const [items, setItems] = useState([ { id: 1, completed: true }, { key: 2, complete: true }, { key: 3, complete: true } ]) I want to add a new object and change the ...

AngularJS input verification

I'm struggling to validate JSON input using Angular. Although I know it can be achieved with a custom directive, I lack the expertise to implement one myself. Therefore, I've resorted to trying to validate the input using ng-change instead. This ...

Is there a way to refresh autocomplete/autofill after form submission with a custom JavaScript function?

I've developed a Vue application that includes a form. Once the user clicks on submit, an Ajax request is made using Axios through a JavaScript function. The data being sent is a custom JSON object that I have constructed by combining the information ...

Create new instances of Backbone Models using an existing Backbone Model as a template

Within my app, I am planning to include a configuration file called config.json as a Backbone Model. Here is an example of how it will be loaded: var Config = Backbone.Model.extend({ defaults: { base: '' }, url: 'config. ...

Using the splice() method to remove an item from an array may cause unexpected results in React applications

Dynamic input fields are being created based on the number of objects in the state array. Each field is accompanied by a button to remove it, but there seems to be unexpected behavior when the button is clicked. A visual demonstration is provided below: ...

Using shortcode to enhance wordpress post content

I am trying to implement a feature similar to the one found at http://jsfiddle.net/theimaginative/gA63t/ within a wordpress post. I have attempted to create a shortcode for inserting this into a post, but I am encountering difficulties. While I have been s ...

What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

Tips on leveraging dynamic queries in your REST API usage

As a new Javascript learner, I am experimenting with creating a basic rest api using node.js. Currently, I have set up a database called testDb and a table named testMeasurement in influxdb. The testMeasurement table consists of the columns DateOfBirth, ID ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Updating the contents of one specific div without affecting all other divs with the same class

Below is the HTML code snippet in question: <a class="btn test-btn test-btn-1"> <span>Content 1</span> </a> This particular code block appears multiple times on the page. The number at the end of test-btn- is dynamically generat ...

Generating dynamic slots in VueJS allows for the creation of

Creating slots dynamically from an array is my current task. After some tinkering, I've managed to make it work using the following code snippet: <template v-for="(department,id) in departments" v-slot:[id]="record"> < ...

During post-processing, the elimination of lens flares can sometimes lead to an error known as "copyTexImage2D: framebuffer is

After looking at the lens flares example here: , I'm encountering an issue with post-processing this particular scene. The blocks display correctly, but the light sources and lens flares are missing. Additionally, I am receiving several warnings in t ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...