Abubakar Ahmad
Abubakar Ahmad

Reputation: 2583

Get the URL of an image from HTML input tag

I want to get the base64 of an image with Javascript.

An answer from here, https://stackoverflow.com/a/20285053/5065874 solved part of my problem.

Basically, he implemented this function:

function toDataUrl(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        var reader = new FileReader();
        reader.onloadend = function() {
            callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
}

And used it like this:

toDataUrl('http://example/url', function(base64Img) {
    console.log(base64Img);
});

But the problem is I don't have a url to pass to toDataUrl(url, callback), rather I have an image input tag on my HTML page:

<form id="myId">
    <input type="image" name="myImage">
</form>

So what should I pass to toDataUrl() in order for the function to work correctly?

Upvotes: 0

Views: 1755

Answers (1)

Barmar
Barmar

Reputation: 781741

You should pass the src attribute of the input element, since it should contain the URL that it displays.

toDataUrl(document.getElementsByName('myImage')[0].src, function...)

Upvotes: 1

Related Questions