node集成tinypng的图片压缩及上传功能实现

const base64Img = require('base64-img');
const fs = require('fs');
const request = require('request');
const Https = require('https');

const TINYIMG_URL = ['tinyjpg.com', 'tinypng.com'];// tinyjpg的域名
function RandomHeader() { // 随机生成ip,避免上传数量被限制
  const ip = new Array(4).fill(0).map(() => parseInt(Math.random() * 255, 10)).join('.');
  const index = Math.round(Math.random(1));
  return {
    headers: {
      'Cache-Control': 'no-cache',
      'Content-Type': 'application/x-www-form-urlencoded',
      'Postman-Token': Date.now(),
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
      'X-Forwarded-For': ip,
    },
    hostname: TINYIMG_URL[index],
    method: 'POST',
    path: '/web/shrink',
    rejectUnauthorized: false,
  };
}
function UploadImgToTiny(file) {
  const opts = RandomHeader();
  return new Promise((resolve, reject) => {
    const req = Https.request(opts, res => res.on('data', (data) => {
      const obj = JSON.parse(data.toString());
      if (obj.error) {
        reject(obj.message);
      } else {
        resolve(obj);
      }
    }));
    req.write(file, 'base64');
    req.on('error', e => reject(e));
    req.end();
  });
}
function DownloadImg(url) {
  return new Promise((resolve) => {
    request({ url, encoding: 'base64' }, (error, res, body) => {
      resolve(body);
    });
  });
}

// 客户端上传调的接口逻辑
  async imgUpload(img,tinyFlag) {
    let base64_str= base64Img.base64Sync(img.path);// 图片转成base64
    if(tinyFlag==="true"){ // 如果开启压缩
      const tiny=await UploadImgToTiny(fs.readFileSync(img.path, "base64"));// 上传到tinypng
      const base64ImgData = await DownloadImg(tiny.output.url);// 从tinypng的域名下载到本地生成base64
      base64_str= "data:image/png;base64,"+base64ImgData// 
    }
    return new Promise((res) => {// 上传到本地的内部服务
      request({
        url: 'xxx',
        formData: {
          base64_str
        },
      }, (error, response, body) => {
        if (error) throw new Error(error);
        res(JSON.parse(body));
      });
    });
  }



你可能感兴趣的:(node集成tinypng的图片压缩及上传功能实现)