简体   繁体   English

从HTML输入标签获取图像的URL

[英]Get the URL of an image from HTML input tag

I want to get the base64 of an image with Javascript. 我想用Javascript获取图像的base64。

An answer from here, https://stackoverflow.com/a/20285053/5065874 solved part of my problem. 来自这里的答案https://stackoverflow.com/a/20285053/5065874解决了部分问题。

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: 但问题是我没有一个url传递给toDataUrl(url, callback) ,而我有我的HTML网页上的图像输入标签:

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

So what should I pass to toDataUrl() in order for the function to work correctly? 那么,为了使函数正常工作,我应该将什么传递给toDataUrl()

您应该传递input元素的src属性,因为它应该包含它显示的URL。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM