upload.js 1.93 KB
'use strict';

const fs = require('fs');
const _ = require('lodash');

const utils = require('../models/utils');
const yohoApi = global.yoho.API;

const AllowedBucket = {
    sns: 'sns',
    evidenceImages: 'evidenceImages'
};

const uploadImg = (req, res, next) => {
    let files = req.files && req.files.file || [];
    let errTip = null;

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

    req.body.files = [];
    files.forEach(file => {
        let types = file.type.split('/');

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

        if (file.size > 10 * 1024 * 1024) {
            errTip = '上传文件尺寸太大!';
        }
        req.body.files.push(fs.createReadStream(file.path));
    });

    if (errTip) {
        return res.status(403).send({
            message: errTip
        });
    }

    const bucket = AllowedBucket[req.body.bucket];

    if (!bucket) {
        return res.json({
            code: 400,
            message: '参数错误'
        });
    }

    Promise.all(
        req.body.files.map(f => {
            return yohoApi.postFile('', {
                bucket: req.body.bucket,
                file: f,
                uid: req.user.uid.toString(),
                method: 'yoho.fileupload'
            }).then(result => {
                if (result.code !== 200) {
                    return Promise.reject(Error('上传出错'));
                }

                return result;
            });
        })
    ).then(result => {
        const data = result.reduce((t, r) => {
            t.images.push(utils.getUploadImgAbsoluteUrl(_.get(r, 'data'), req.body.bucket));
            t.imagesList.push(_.get(r, 'data'));
            return t;
        }, { images: [], imagesList: [] });

        res.json({
            code: 200,
            data,
            message: '上传成功'
        });
    }).catch(next);
};

module.exports = {
    uploadImg
};