Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax.

Here is an example of the code I am working on:

const load = async () => {
  loaded.value = false

  try {
    const res = await axios.get(src.value, {
      headers: { 'X-Chat-Session': sessid }
    })

    console.log(res.data) // "����\u0002IExif\u0000\u0000MM\u0000*\u0000\u0000\u0000\u0008\u0000\u0007\u0001\u0000\u0000\u0003\u0000\u0000\u0000... 

    loaded.value = true
    emit('loaded')
  } catch (e) {
    emit('loadingError', e)
  }
}

My goal is to

<my image container>.appendChild(new Image(res.data))

Alternatively, it would be ideal if I could insert the binary response into the src attribute of an existing <img> element.

Important notes:

  • I do not have control over the server side
  • I cannot use service workers
  • Base64 operations are not recommended

That's all. I appreciate your help!

Answer №1

Give this a shot:

const fetchImageData = async () => {
  imageDataLoaded.value = false

  try {
    const response = await axios.get(imageSourceUrl.value, {
      responseType: 'blob', 
      headers: { 'X-Chat-Session': sessionId }
    })

    console.log(response.data)
    const imageUrl = URL.createObjectURL(response.data)
    <image element>.src = imageUrl;

    imageDataLoaded.value = true
    emit('imageDataLoaded')
  } catch (error) {
    emit('imageLoadingError', error)
  }
}

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

Which JavaScript framework tackles the challenges of managing asynchronous flow, callbacks, and closures?

I have a strong aversion to JavaScript. I find it to be quite messy and disorganized as a language. However, I recognize that my lack of proficiency in coding with it may contribute to this perception. These past few days have been incredibly frustrating ...

Determining the minimum and maximum values of a grid using props in a React component

I have created a code for a customizable grid screen that is functioning perfectly. However, I am facing an issue where I want the minimum and maximum size of the grid to be 16 x 100. Currently, when a button is clicked, a prompt window appears asking for ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

Flowing Waterways and Transmission Control Protocol

I have a unique piece of code that I recently discovered. After running it, I can connect to it using a Telnet client. const network = require('networking'); //creating the server const server = network.createServer(function (connection) { ...

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

JQuery method for extracting a specific span's content from a div

I am faced with extracting specific text from a span within a div element. Below is the code snippet for my Div: '<div class="dvDynamic_' + pid + '"><p hidden="true">'+pid+'</p><span class="count_' + pid ...

Step-by-step guide on resolving AngularJS Issue: [$injector:modulerr]

I'm encountering an issue with Angular JS where I'm receiving the following error: jquery.js:7993 Uncaught Error: [$injector:modulerr] Failed to instantiate module application due to: Error: [$injector:nomod] Module 'application' is no ...

Error encountered when importing a Material-UI component: Unable to load a module from @babel/runtime

Struggling to compile the index.js file with rollup: import React from "react"; import ReactDOM from "react-dom"; import Grid from "@material-ui/core/Grid"; ReactDOM.render( <React.StrictMode> <Grid conta ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

What is the best way to incorporate several php files into a WordPress post?

I have developed a system that retrieves information from a database and presents it in multiple text files. Now, I am looking to move this system to a page on a WordPress website. I have already created a custom page named page-slug.php and added the ne ...

What is the best way to display a list of items in Vue JS while maintaining the

Looking to display my Vue.js list in reverse order using v-for without altering the original object. The default HTML list displays from top to bottom, but I want to append items from bottom to top on the DOM. Telegram web messages list achieves this wit ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

Using JQuery to toggle a fixed div at the bottom causes all other divs to shift upwards

I'm currently working on a chat feature using node JS, and while the functionality is perfect, I've run into an issue with the CSS aspect of it. The problem arises when we have multiple tabs and clicking on just one causes all the tabs to move u ...

Disallow/bound the position of the marker on Google Maps

Is there a way to restrict the placement of markers on a map? I am looking for a solution that allows me to limit the marker position within a specific area, such as a town, with a radius of 10km. It should prevent users from dragging or creating new mark ...

creating a form layout with inline buttons

I have encountered an issue with aligning 2 buttons and a form with input type in a single line. Even though I have tried different approaches, I am unable to achieve the desired inline layout. Here is my current setup: .btn-registerLayout { backgr ...

Modifying image size by adjusting width before sending it through a header in php

So, I have this little snippet of code that does some magic with random images and redirects them to another page. The twist is I'm trying to make it handle image widths that exceed a certain maximum width. I made some progress but then hit a roadbloc ...

Applying a dynamic translate3d transformation on the ::after element using CSS3

My current challenge involves manipulating a pseudo ::after element using translate3d If I hardcode the values, it's straightforward: div::after { ... transform: translate3d(40px, 40px, 0); } Now, I want to dynamically set the value for the ...

The jQuery upload feature fails to function properly when attempting to upload multiple images simultaneously on a single webpage

Overview: I am currently in the process of developing an instant upload feature using Jquery/Ajax. The goal is to display a Fancybox with an upload field when a user double-clicks on an image. Once the user selects an image, it should be uploaded and the s ...

Enhance the efficiency of time tracking function

I have been using a nodejs module to track the execution time of different parts of my application. // polyfill for window.performance.now var performance = global.performance || {} var performanceNow = performance.now || performance.mozNow ...