How do I download a dynamically created image from backend without using <a>
attribute? I want to download the QR code generated.
JS file:
var textarea = document.getElementById("textarea"),
content = document.getElementById("content");
var data = encodeURIComponent(textarea.value),
size = document.getElementById("size").value,
chart = "http://chart.googleapis.com/chart?cht=qr&chs=" + size +
"x" + size + "&choe=UTF-8&chld=L|0&chl=" + data;
if (data === "") {
alert("Please enter a valid data!");
textarea.focus();
content.style.display = "none";
} else {
content.style.display = "";
document.getElementById("qrcode").src = chart;
}
document.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 13) {
}
});
HTML code:
<p>Enter an URL or some text bellow and hit the Generate button (
<kbd>Ctrl</kbd>+
<kbd>Enter</kbd>)!</p>
<textarea id="textarea" autofocus></textarea>
<label for="size">Size (px):</label>
<input id="size" type="number" value="150" min="50"
max="500" step="50">
<button onclick="App.genQRcode()">Generate</button>
<div id="content" style="display: none;">
<p><img id="qrcode" src="" /></p>
</div>
答案 0 :(得分:0)
据我了解,您将需要使用标签。您能做的是在JS中动态创建一个标签,向图像添加href,然后触发点击?
var thisLink = document.createElement("a"),
thisLink.id = "generatedQRCode",
thisLink.href= document.getElementById("qrcode").src,
thisLink.download = "download";
document.body.appendChild(thisLink);
document.getElementById("generatedQRCode").click();
document.getElementById("generatedQRCode").remove();