upload.js 1.44 KB

const fs = require('fs');
const _ = require('lodash');
const request = require('request-promise');
const log = global.yoho.logger;

const upload = ({ files, type, size, bucket }) => {
  let reqFiles = [];
  let errTip = '';

  if (!_.isArray(files)) {
    files = [files];
  }

  size = size || 10 * 1024 * 1024;

  files.forEach(file => {
    let fileType = file.type.split('/');


    if (!fileType || (type && fileType[0] !== type)) {
      errTip = '上传文件格式不正确!';
    }

    if (file.size > size) {
      errTip = '上传文件尺寸太大!';
    }

    if (file.path.indexOf('.') < 0) {
      let newPath = `${file.path}.${fileType[1]}`;

      fs.renameSync(file.path, newPath);
      file.path = newPath;
    }

    reqFiles.push(fs.createReadStream(file.path));
    reqFiles.push(file.name);
  });

  if (errTip) {
    return Promise.resolve({
      code: 403,
      message: errTip
    });
  }

  return request({
    method: 'post',
    url: 'http://upload.static.yohobuy.com',
    formData: {
      fileData: reqFiles,
      project: bucket
    },
    json: true
  }).catch(err => {
    let message = 'file upload error';

    log.error(message, JSON.stringify(err));
    return {
      code: 403,
      message
    };
  });
}

const uploadIdCard = (req, res, next) => {
  upload({
    files: req.files && req.files.file || [],
    type: 'image',
    bucket: 'yohocard'
  }).then(res.json).catch(next);
}

module.exports = {
  uploadIdCard
};