我尝试用QRcode.js库创建QR代码。从UI开始,我可以手动单击下载按钮来下载它,但是我会自动下载而不点击按钮。
根据我的代码。
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);
}如果我使用按钮点击和手动下载将对我很好,但我想减少太多的步骤。
我想我差不多完成了,但失败了。
有人能告诉我如何自动下载吗?
提前谢谢你。
发布于 2022-02-11 09:11:46
我过去曾遇到过这个问题,我通过创建一个小的util函数来解决这个问题,我可以在按下按钮时调用它。但是在函数结束时直接调用它应该与用户单击具有相同的结果,有效地不需要用户输入就自动下载QR代码。
export function download(blob, filename) {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}如果您得到的对象是Blob,我猜您可以尝试将generate作为第一个参数传递。否则,您可能需要在此之前转换它。
发布于 2022-02-11 09:35:56
我完成了我的目标,添加了您在代码底部共享的源代码,然后添加了这个函数将dataURL转换为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;
}“谢谢你,”詹马科·伦古奇(Gianmarco Rengucci )说。
https://stackoverflow.com/questions/71077456
复制相似问题