Blame view

apps/common/controllers/upload.js 1.43 KB
刘传洋 authored
1 2 3 4 5 6 7 8 9 10
'use strict';

const request = require('request-promise');
const fs = require('fs');
const _ = require('lodash');

const utils = require('../models/utils');

const uploadImg = (req, res, next) => {
    let files = req.files && req.files.file || [];
刘传洋 authored
11
    let errTip = null;
刘传洋 authored
12 13 14 15 16 17 18

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

    req.body.files = [];
    files.forEach(file => {
刘传洋 authored
19 20 21 22 23 24 25

        let types = file.type.split('/');

        if (!types || types[0] !== 'image') {
            errTip = '上传文件格式不正确!';
        }
刘传洋 authored
26
        if (file.size > 10 * 1024 * 1024) {
刘传洋 authored
27 28
            errTip = '上传文件尺寸太大!';
        }
刘传洋 authored
29 30 31 32
        req.body.files.push(fs.createReadStream(file.path));
        req.body.files.push(file.name);
    });
刘传洋 authored
33
    if (errTip) {
刘传洋 authored
34
        return res.status(403).send({
刘传洋 authored
35 36 37 38
            message: errTip
        });
    }
刘传洋 authored
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    request({
        method: 'post',
        url: 'http://upload.static.yohobuy.com',
        formData: {
            fileData: req.body.files,
            project: req.body.bucket
        },
        json: true
    }).then(function(result) {

        if (result && result.code === 200) {
            result.data = result.data || {};
            result.data.images = _.map(_.get(result, 'data.imagesList'), (it) => {
                return utils.getUploadImgAbsoluteUrl(it, req.body.bucket);
            });
        }

        res.json(result);
    }).catch(next);
};

module.exports = {
    uploadImg
};