node生成二维码并打包下载
node生成二维码并打包下载
node生成二维码并打包下载-MakerLi

1.如何使用node生成二维码

引入qrcode插件;

 cnpm i qrcode -S

引入函数并且封装成函数

async createQr(url, name) {
    return await new Promise((resolve, reject) => {
      QRCode.toFile(name, url, {
        color: {
          dark: '#ffffff',  
          light: '#0000'
        }
      }, function (err) {
        if (err) throw resolve(err);
        resolve('成功');
      });
    }).then(data => data);
  };

直接调用

await this.createQr('http://baidu.com', '1.png');//指定文件夹 let res = await this.createQr('http://baidu.com', path.join(config.dir,'/tmp/6.png'));

2.引入jszip压缩

 cnpm i jszip -S

引入并封装函数

  async toZip (fileName, { delSource = false } = {}) {
    return await new Promise(async(resolve, reject) => {
    var zip = new JSZip();
        let file = fileName+'.png';
        let content =await  fs.readFileSync(path.join(config.dir,file));
        zip.file(file, content);
      let _this=this;
    // 压缩
/** 批量
        let fileArr=await fs.readdirSync(path.join(config.dir,'/tmp'))
 
        for(let i=0;i<fileArr.length;i++){
          let content =await  fs.readFileSync(path.join(config.dir,'/tmp/'+fileArr[i]));
          zip.file(fileArr[i]+'.png', content);
        }
  */
      zip.generateAsync({
          // 压缩类型选择nodebuffer,在回调函数中会返回zip压缩包的Buffer的值,再利用fs保存至本地
          type: "nodebuffer",
          // 压缩算法
          compression: "DEFLATE",
          compressionOptions: {
              level: 1
          }
      }).then(function (content) { 
          let zip = fileName + '.zip';
          let url=path.join(config.dir,zip);
          // 写入磁盘
          fs.writeFile(url, content, function (err) {
              if (!err) {
                  // 是否删除源文件
                  resolve(url)
                  if (delSource) {
                     //删除文件 
                  }
            } else {
                console.log(zip + '压缩失败');
            }
        });
    });
  });
};

直接在egg中调用

  let res = await this.createQr('http://baidu.com', '1.png');
  let url= await this.toZip('1');
  this.ctx.attachment(url);
  this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
  this.ctx.body = fs.createReadStream(url);