How to show Laravel Storage image with Ajax?

Asked

Viewed 150 times

0

I have a project that analyzes images and returns a frame and some variables, within the /storage/imagens/ where I save the image analyzed but I do not know how to make it be pulled by ajax and placed inside the src of a div or img. I was creating a Controller that looked for the file inside the images and then treated it, put it in a Json and then ajax consumed and inserted it into src. Someone can give me a method but easy to do this?

1 answer

0

If your controller directly serves an image file, you can create an Blob, using the fetch, and then generate a URL.

In the example below, the URL we are requesting is any image file. But in your case, just switch to the URL of your application that serves the image file.

Anyway, you can do something like this:

// Coloque a URL que retorna a imagem do controller:
const endpoint = 'https://lffg-archive.github.io/sopt/img.png?img=png';

const placeholder = document.querySelector('#img-placeholder');

async function loadImage(uri, el) {
  try {
    const response = await fetch(uri);

    if (response.status >= 400) {
      console.error('Houve algum erro ao carregar.');
      return false;
    }

    const blob = await response.blob();

    // Criamos uma URL a partir do blob:
    const url = URL.createObjectURL(blob);

    // Adicionamos a URL gerada na imagem:
    el.src = url;
    return true;
  } catch (error) {
    console.error('Houve algum erro:', error.message);
    return false;
  }
}

loadImage(endpoint, placeholder)
  .then(() => console.log('Done.'));
<img id="img-placeholder" width="200" height="200" />

By way of curiosity: this is how many videos on the internet are loaded, although most of the time several processes are added to avoid the download of those files.


Or you can just add the src image directly, without complicating! :)

<img src="{{ $image_url }}" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.