Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
How to display a base64 image that is inside a .txt file on the img src

Below is my img tag as you can see the src is a .txt file

<img id="loading" src="assets/images/loader_gif.txt" alt="Red dot" />

Below is the value of the loader_gif.txt its a base64 image. enter image description here

The problem is the image doesn't show if I do it like this. But if I put directly the whole base64 on the src, it will display the image.

Is there anything I am missing?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A .txt is not a supported format to directly use as an image src, so that's not possible.

If the content inside your .txt doesn't change, I would recommend to directly use the base64 as an image src. You already said you did it (which is working), so just for those people who don't know how to use base64 as image src. Heres an example

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" />

In order to use the txt file however, you would have to load the file via Javascript, get the contents of the file and add the base64 as an image src. XMLHttpRequest would be one way to get the contents.

const client = new XMLHttpRequest();

// instead of foo.txt you need to add your .txt file of course
client.open('GET', '/foo.txt'); 

client.onreadystatechange = () => {
  // Make sure the request was done
  if (client.readyState === XMLHttpRequest.DONE) {
    const status = client.status;

    // make sure the request ended up successfully
    if (status === 0 || (status >= 200 && status < 400)) {
      // If request was successful, grab the base64 from the response
      const base64Image = client.responseText;
      console.log(base64Image);

      // add the base64 as image src
      const image = document.querySelector('#loading');
      image.src = base64Image;
    } else {
      // In case the request to get the .txt content failed, you can do something else.
      // For example add a static fallback image
    }
  }
}
client.send();

One additional note: There may be cases where the processing power of either client-side or server-side is (or even both) is very low. For example on low-end phones or shared web hosting. So you have to know it could take a while until the image is displayed since all those steps have to run first:

  1. get HTML content from page (here an empty / broken image is shown since nor src is set yet)
  2. javascript need to be parsed and run
  3. the HttpRequest will be executed
  4. the server need to respond with the contents of your txt
  5. JS need to add the image src

So in order to not have a broken image or flickering while all the image loading is done, you can deliver a placeholder image right in html. Something which is small in file size and static. As soon as image.src = base64Image; runs, it would be replaced.

But in your case, it's saying "loader_gif", so I guess it's already for some loading action. Having a placeholder image until a loader image is being loaded via Javascript seems a bit "over the top" for a loading action.

about 4 years ago · Juan Pablo Isaza Relatório

0

Your use-case is not much different than having the browser load the actual image just as it does any other resources. I assume you have already considered having the image as an actual image.

Because the image is not really an image, you need to manage that. In your case, it is "almost" in an image format, so the processing is minimal, meaning you just need to get the data from the file and set it at the src of the image element.

<body>
    <img id="loading" alt="Red dot" />

    <script>
        fetch('/assets/images/loader_gif.txt').then(response => response.text())
        .then(b64img => {
            document.getElementById('loading').src = b64img;
        })
    </script>
</body>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda