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 }}" />