upload.js 1.92 KB

'use strict';
const _ = require('lodash');
const Router = require('koa-router');
const rp = require('request-promise');
const fs = require('fs');

const r = new Router();

const bucket = 'goodsimg';

const _getUploadImgAbsoluteUrl = (url, bucket) => {
    if (!url) {
        return null;
    }

    let urlArr = url.split('/'),
        stag = urlArr[urlArr.length - 1].substr(0, 2),
        domain = `static.yhbimg.com/${bucket}`;

    url = domain + url;
    if (stag === '01') {
        return `//img11.${url}`;
    } else if (stag === '03') {
        return `//flv01.${url}`;
    } else {
        return `//img12.${url}`;
    }
};

const upload = {
    async image(ctx) {
        let files = _.get(ctx, 'request.body._files.file');
        let errTip;

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

        const renderFiles = [];
        files.forEach(file => {

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

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

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

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

        await rp({
            method: 'post',
            url: 'http://upload.static.yohobuy.com',
            formData: {
                fileData: renderFiles,
                project: 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 _getUploadImgAbsoluteUrl(it, bucket);
                });
            }

            ctx.response.body = result;
        });
    }
};

r.post('/image', upload.image);

module.exports = r;