Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Descarga programáticamente la imagen QR

Traté de crear un código QR con la biblioteca QRcode.js. A partir de la interfaz de usuario, puedo hacer clic manualmente en el botón descargar para descargarlo, pero lo haría automáticamente sin hacer clic en el botón.

Base en mi código a continuación.

 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); }

Si uso el botón para hacer clic y descargar a mano, funcionará bien para mí, pero quiero reducir demasiados pasos.

Creo que casi termino aquí, pero fallé.

¿Alguien podría mostrarme cómo descargar automáticamente?

Gracias de antemano.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Tuve este problema en el pasado y lo solucioné creando una pequeña función de utilidad que puedo invocar al presionar un botón. Pero invocarlo directamente al final de su función debería tener el mismo resultado que un clic del usuario, descargando automáticamente el código QR sin la intervención del usuario.

 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); }

Supongo que podría intentar pasar generate como primer parámetro si el objeto que está obteniendo es un blob. De lo contrario, probablemente necesitarás convertirlo antes.

about 4 years ago · Juan Pablo Isaza Report

0

Hice mi objetivo agregando la fuente que compartiste en la parte inferior de mi código y luego agregué esta función para convertir dataURL a 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; }

Muchas gracias @Gianmarco Rengucci te califico

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!