How to set img.src in HTML from responseText in Javascript?

Viewed 647

I followed this answer & file downloading is successful. The facing problem is to set downloaded image file into the img.src tag.

Image link: https://images.pexels.com/photos/853199/pexels-photo-853199.jpeg?crop=entropy&cs=srgb&dl=aerial-view-of-seashore-near-large-grey-rocks-853199.jpg&fit=crop&fm=jpg&h=4000&w=6000

Code:

function onReadyState(e){

    let r = e.target;
    if(r.readyState != 4 || r.status != 200){
        return
    }
    console.log(r)
    let img = document.getElementById('downloaded-img')
    let base64  = btoa(r.response)
    img.src = 'data:image/jpg;base64,'+base64
}

I tried to convert responseText into base64 to set img.scr for display downloaded image. But I got error,

Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range. at XMLHttpRequest.downloadCompleted

Then I used below code by following this answer.

   let base64  = btoa(unescape(encodeURIComponent(r.responseText)))

The error is gone. But img is still whitespace. How can I resolve it? Thanks in advance...

Update: I used this link. It throws below error,

Access to XMLHttpRequest at 'https://cdn.dribbble.com/users/93493/screenshots/1445193/notfound.png' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I used this link too, Didn't got any error But I got same blank area instead of image.

enter image description here

2 Answers

btoa receive a string as an argument, but you have a stream. You can use URL.createObjectURL for get a blob url

const url = 'https://images.pexels.com/photos/853199/pexels-photo-853199.jpeg?crop=entropy&cs=srgb&dl=aerial-view-of-seashore-near-large-grey-rocks-853199.jpg&fit=crop&fm=jpg&h=4000&w=6000';
const img = document.querySelector('img');

fetch(url).then(data => data.blob()).then(blob => {
    const src = URL.createObjectURL(blob);
    img.src = src;
}).catch(err => console.log(err));
<img height="150"/>

For download an image from url:

var a = document.createElement('a');
a.href='https://images.pexels.com/photos/853199/pexels-photo-853199.jpeg?crop=entropy&cs=srgb&dl=aerial-view-of-seashore-near-large-grey-rocks-853199.jpg&fit=crop&fm=jpg&h=4000&w=6000';
a.download='filname.jpg';
document.body.appendChild(a);
a.click();
a.remove()

One long way is to use FileReader that assuming you received the data as blob so this should work (hopefully) :

xml = new XMLHttpRequest()
xml.open("GET", "YOUR URL", true)
xml.responseType = "blob"
var blob
xml.onload = function(e){blob = xml.response;}
file = new FileReader()
var base64
file.onloadend = function() {base64 = file.result}
file.readAsDataURL(blob)
img = document.getElementById('downloaded-img')
img.src = base64
Related