JS 批量生成二维码打包zip下载

邱秋 • 2024年04月20日 • 阅读:111 • nodejs javascript

拿到一些链接, 要把链接生成二维码图片, 然后压缩生成的二维码为zip包, 最后下载

准备工作

安装依赖

npm install qrcode jszip

生成二维码

const QRCode = require('qrcode');

//传入 url 和要生成的文件名
async generateQRCode(url, filename) {
  try {
    const qrCode = await QRCode.toDataURL(url);
    // You can save the QR code image or use it as needed
    // Here, we are just printing the filename and data URL
    // console.log('QR Code generated for', filename);
    // console.log('Data URL:', qrCode);

    return { filename, qrCode };
  } catch (error) {
    console.error('Error generating QR Code for', filename, error);
    return null;
  }
}

生成批量数据

const JSZip = require('jszip');

async downLoadCodeZip() {
  let qrCodeDataArray = []
  let urlList = [{url:'https://',file_name:'xxx'},...]
  for (let j = 0; j < urlList.length; j++) {
    let x = urlList[j]
    let data = await this.generateQRCode(x.url, x.file_name)
    qrCodeDataArray.push(data)
  }
  await createZipFile(qrCodeDataArray)
}

生成zip包和下载

async createZipFile(qrCodeDataArray) {
  const zip = new JSZip();
  qrCodeDataArray.forEach(({ filename, qrCode }) => {
    zip.file(`${filename}.png`, qrCode.split('base64,')[1], { base64: true });
  });

  // const zipContent = await zip.generateAsync({ type: 'nodebuffer' });
  const zipContent = await zip.generateAsync({ type: 'blob' });

  const zipBlob = new Blob([zipContent], { type: 'application/zip' });
  const zipUrl = URL.createObjectURL(zipBlob);

  const downloadLink = document.createElement('a');
  downloadLink.href = zipUrl;
  downloadLink.download = `zipFile.zip`;

  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);

  // fs.writeFileSync('qrcodes.zip', zipContent);

  console.log('Zip file created: qrcodes.zip');
}

收工.

我,秦始皇,打钱!