node.js 图片上传 接口 实现

'use strict';

const fs = require('fs');
const path = require('path');
const sendToWormhole = require('stream-wormhole');
const images = require("images");
var mkdirs = require('mkdirs');
var zipper = require('zip-local');
var wkhtmltoimage  = require('wkhtmltoimage');
var wkhtmltopdf  = require('wkhtmltopdf');
function saveStream(stream, filepath, dir) {
  return new Promise((resolve, reject) => {
    if (filepath.indexOf('/read-error-') > 0) {
      stream.once('readable', () => {
        const buf = stream.read(10240);
        console.log('read %d bytes', buf.length);
        setTimeout(() => {
          reject(new Error('mock read error'));
        }, 1000);
      });
    } else {

      if (!fs.existsSync(dir)) {
        mkdirs(dir)
      }

      const ws = fs.createWriteStream(filepath);
      stream.pipe(ws);
      ws.on('error', reject);
      ws.on('finish', resolve);
    }
  });


}


module.exports = app => {
  class UploadController extends app.Controller {


    * img() {
      
      const stream = yield this.ctx.getFileStream();

      let file_dir = new Date().Format("yyyyMMdd");
      let file_name = new Date().getTime() + stream.filename.substring(stream.filename.lastIndexOf("."), stream.filename.length);
      let filepath = path.join(this.app.config.uploadDir, `${file_dir}/${file_name}`);

      // if (stream.fields.title === 'mock-error') {
      //   filepath = path.join(this.app.config.baseDir, `logs/not-exists/dir/${stream.filename}`);
      // } else if (stream.fields.title === 'mock-read-error') {
      //   filepath = path.join(this.app.config.baseDir, `logs/read-error-${stream.filename}`);
      // }
      
      this.logger.warn('Saving %s to %s', file_name, filepath);
      try {
        yield saveStream(stream, filepath, path.join(this.app.config.uploadDir, `${file_dir}`));
      } catch (err) {
        yield sendToWormhole(stream);
        throw err;
      }


      this.ctx.body = {
        success: true,
        msg: "error message",
        file_path: `/public/upload/${file_dir}/${file_name}`
      }

    }


    * zipimg() {
      var ziptype = 'eggimg0';
      if(this.ctx.query.type!=null&&this.ctx.query.type=='480'){
        ziptype = 'eggimg480'
      }
      console.log(ziptype)
      const stream = yield this.ctx.getFileStream();

      let file_dir = new Date().Format("yyyyMMdd");
      let file_name = new Date().getTime() + stream.filename.substring(stream.filename.lastIndexOf("."), stream.filename.length);
      let filepath = path.join(this.app.config.uploadDir, `${file_dir}/eggimg0/${file_name}`);
      let file480path = path.join(this.app.config.uploadDir, `${file_dir}/eggimg480/${file_name}`);


      this.logger.warn('Saving 0: %s to %s', file_name, filepath);
      this.logger.warn('Saving 480: %s to %s', file_name, file480path);
      try {
        yield saveStream(stream, filepath, path.join(this.app.config.uploadDir, `${file_dir}/eggimg0`));

        if (!fs.existsSync(path.join(this.app.config.uploadDir, `${file_dir}/eggimg480`))) {
          fs.mkdirSync(path.join(this.app.config.uploadDir, `${file_dir}/eggimg480`))
        }

        images(filepath) //Load image from file 
          //加载图像文件
          .size(480) //Geometric scaling the image to 400 pixels width
          //等比缩放图像到400像素宽
          //.draw(images("logo.png")) //Drawn logo at coordinates (10,10) , 10, 10
          //在(10,10)处绘制Logo
          .save(file480path, { //Save the image to a file,whih quality 50
            quality: 100 //保存图片到文件,图片质量为50
          });

      } catch (err) {
        yield sendToWormhole(stream);
        throw err;
      }


      this.ctx.body = {
        success: true,
        msg: "error message",
        file_path: `/public/upload/${file_dir}/eggimg480/${file_name}`
      }

    }

      /**
       * 上传录音
       */
    *voice(){
          const stream = yield this.ctx.getFileStream();

          let file_dir = new Date().Format("yyyyMMdd");
          let file_name = new Date().getTime() + stream.filename.substring(stream.filename.lastIndexOf("."), stream.filename.length);
          let filepath = path.join(this.app.config.uploadDir, `voice/${file_dir}/${file_name}`);
          this.logger.warn('Saving voice: %s to %s', file_name, filepath);

          try {
              yield saveStream(stream, filepath, path.join(this.app.config.uploadDir, `voice/${file_dir}`));

              if (!fs.existsSync(path.join(this.app.config.uploadDir, `voice/${file_dir}`))) {
                  fs.mkdirSync(path.join(this.app.config.uploadDir, `voice/${file_dir}`))
              }
          } catch (err) {
              yield sendToWormhole(stream);
              throw err;
          }
          this.ctx.body = {
              success: true,
              file_path: `/public/upload/voice/${file_dir}/${file_name}`
          }
    }
  }
  return UploadController;
};

猜你喜欢

转载自blog.csdn.net/ZkD953/article/details/82593119