Tendría un servidor que está cargando una imagen en la web usando una plantilla como:
<body><img src="data:image/jpg;base64,{{.Image}}"></body>` Donde {{.Image}} es un búfer de datos.
Estoy tratando de recopilar este búfer a través de un cliente, solo JavaScript, usando fetch y agregarlo al elemento <img> , así que escribí lo siguiente:
<html> <head></head> <body> <img id="photo" alt="Girl in a jacket" width="500" height="600"> </body> <script type="text/javascript"> const myRequest = new Request('http://localhost:8080/blue/', { method: 'GET', headers: new Headers(), type: "arraybuffer", mode: 'cors', cache: 'default', }); fetch(myRequest) .then(response => { var arrayBufferView = new Uint8Array(response); var blob = new Blob([arrayBufferView], {type: "image/jpeg"}); return blob}) .then(myBlob => { var urlCreator = window.URL || window.webkitURL; var imageUrl = urlCreator.createObjectURL(myBlob); // var imageUrl = URL.createObjectURL(myBlob); var img = document.querySelector("#photo"); img.src = imageUrl; }); </script> </html> Mientras cargaba la página, obtuve que el contenido del elemento img fuera:
<img id="photo" alt="Girl in a jacket" width="500" height="600" src="blob:null/c94ac446-55c5-4ee5-a492-5286b1935ffb">Y no aparece nada.
¿Cómo puedo arreglar esto?
Pude resolverlo de la siguiente manera:
<html> <head></head> <body> <img id="photo" alt="Girl in a jacket" width="500" height="600"> </body> <script type="text/javascript"> const myRequest = new Request('http://localhost:8080/blue/', { method: 'GET', headers: new Headers(), type: "arraybuffer", mode: 'cors', cache: 'default', }); fetch(myRequest) .then(response => response.blob()) .then(blob => { var reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { var imageUrl = reader.result; var img = document.querySelector("#photo"); img.src = imageUrl; } }); </script> </html>