'Programmatically download the QR image
I tried to create a QR code with QRcode.js library. As of the UI, I can manually click on the button download to download it but I would to download automatically without clicking the button.
Base on my code bellow.
function genQR(link_string){
let qr_code_element = document.querySelector(".qr-code");
if (link_string != "") {
if (qr_code_element.childElementCount == 0) {
generate(qr_code_element, link_string);
} else {
qr_code_element.innerHTML = "";
generate(qr_code_element, link_string);
}
} else {
alert("not valid QR input");
qr_code_element.style = "display: none";
}
}
function generate(qr_code_element, link_string) {
qr_code_element.style = "";
var qrcode = new QRCode(qr_code_element, {
text: link_string,
width: 200,
height: 200,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel: QRCode.CorrectLevel.H
});
let download = document.createElement("button");
// qr_code_element.appendChild(download);
let download_link = document.createElement("a");
download_link.setAttribute("download", "qr.png");
download_link.setAttribute("id", "downloadbtn");
download_link.innerText = "Download";
// download.appendChild(download_link);
let qr_code_img = document.querySelector(".qr-code img");
let qr_code_canvas = document.querySelector("canvas");
if (qr_code_img.getAttribute("src") == null) {
setTimeout(() => {
download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
}, 300);
} else {
setTimeout(() => {
download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
}, 300);
}
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
//I expect the below line will automatically download the QR but nothing fires.
download_link.dispatchEvent(clickEvent);
}
If I use button to click and download by hand will works fine for me but I want to reduce too many steps.
I think I almost done here but failed.
Could anyone show me how to automatic download?
Thank you in advance.
Solution 1:[1]
I done my target by adding the source you shared at the bottom of my code and then added this function to convert dataURL to Blob
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ab], {type: mimeString});
return blob;
}
Thank you very much @Gianmarco Rengucci I rate for you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yenseng |
