I'd a server that is loading an image in the web using a template as:
<body><img src="data:image/jpg;base64,{{.Image}}"></body>`
Where {{.Image}} is a buffer data.
I'm trying to collect this buffer through a client, JavaScript only, using fetch and add it to the <img> element, so I wrote the below:
<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>
While loading the page, I got the img element content to be:
<img id="photo" alt="Girl in a jacket" width="500" height="600" src="blob:null/c94ac446-55c5-4ee5-a492-5286b1935ffb">
And nothing displayed.
How can I fix this?
I was able to solve it as below:
<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>