upload.js 2.2 KB
/**
 * 公共接口
 * @author: jinhu.dong<jinhu.dong@yoho.cn>
 * @date: 2016/07/21
 */

'use strict';

const request = require('request');
const fs = require('fs');

// 获取图片绝对地址
const getImgHost = (url, bucket) => {
    let domain = `static.yhbimg.com/${bucket}`,
        urlArr = url.split('/'),
        num = urlArr[urlArr.length - 1].substr(1, 1),
        url1 = domain + url;

    if (num === '1') {
        return `http://img11.${url1}`;
    } else {
        return `http://img12.${url1}`;
    }
};

// 上传图片
const uploadImg = (req, res) => {
    let i = 0;
    let files;
    let imgs, datas;

    if (req.user.uid) {
        files = [req.files.filename];

        // 如果是单张,则数组化
        if (Object.prototype.toString.call(files) !== '[object Array]') {
            files = [req.files.filename];
        }

        req.body.files = [];
        req.body.fileNames = [];

        for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
            req.body.files[fileIndex] = fs.createReadStream(files[fileIndex].path);
            req.body.fileNames[fileIndex] = files[fileIndex].name;
        }

        request.post({
            url: 'http://upload.static.yohobuy.com',
            formData: {
                fileData: req.body.files,
                project: req.body.bucket
            },
            json: true
        }, (error, httpResponse, rebody) => {
            console.log(httpResponse);
            if (!error && httpResponse.statusCode === 200) {
                imgs = rebody.data.imagesList || [];
                datas = [];

                // 生成图片绝对地址
                for (i = 0; i < imgs.length; i++) {
                    datas.push(getImgHost(imgs[i], req.body.bucket));
                }
            }

            res.json({
                code: 200,
                data: datas[0],
                datas: datas,
                imgs: imgs,
                names: req.body.fileNames,
                message: '上传成功',
                status: true
            });
        });
    } else {
        res.json({
            code: 401,
            message: '用户失效,请重新登录'
        });
    }
};

module.exports = {
    uploadImg
};