common.upload.js 11.5 KB
var request = require('request');
var _ = require('lodash');
var fs = require('fs');
var http = require('http');

var config = global.global.Register;

var Utils = {
    objectToUrl: function (items) {
        var urls = [];
        for (var name in items) {
            if (items.hasOwnProperty(name) && items[name]) {
                urls.push(name + "=" + items[name]);
            }
        }
        return urls.join('&');
    },
    createHttpHeader: function (req) {
        if (req.session && req.session.user) {
            var user=req.session.user;
            return {
                'x-user-id': user.auth.pid,
                'x-user-name': user.auth.account,//防止header中包含中文
                'x-site-type': 1,
                'x-client-ip': req.ip,
                'x-user-brands':typeof user.brands==="string"?user.brands: user.brands.join(',')
            };
        }
    },
    joinImg: function (url) {
        var urlArr = url.split('/');
        var domain = 'static.yhbimg.com/goodsimg';
        var num = urlArr[urlArr.length - 1].substr(1, 1);
        var url1 = domain + url;
        if (num == 1) {
            return 'http://img11.' + url1;
        } else {
            return 'http://img12.' + url1;
        }
    }
};

module.exports = {
    namespace: "common",
    apis: {
        multipart: function (req, callback) {
            var result = {code: "500", message: "接口异常"};
            var httpHeader = Utils.createHttpHeader(req);
            if (!httpHeader) {
                result = {code: "501", message: "用户失效,请重新登录"};
                return callback(null, result);
            }
            var body = req.body;
            //上传excel文件
            if (body.__type == "batch-import") {
                var url = Utils.objectToUrl(body);
                body.file = fs.createReadStream(req.files[body.filename].path);
                request.post({
                    url: config.domain + '/batch/import?' + url,
                    formData: body,
                    headers: httpHeader
                }, function optionalCallback(error, httpResponse, rebody) {
                    if (!error && httpResponse.statusCode == 200) {
                        result = JSON.parse(rebody);
                        result.status = true;
                    }
                    return callback(null, result);
                });
            }
            //上传txt文件
            else if(req.body.__type == "import-txt"){
                req.body.file = fs.createReadStream(req.files[req.body.filename].path);
                request.post({
                    url: config.domain+"/couponSendFile/upload",
                    formData: req.body,
                    headers: httpHeader
                }, function optionalCallback(error, httpResponse, body) {
                    if (error) {
                        return callback(null,error);
                    }
                    if (!error && httpResponse.statusCode == 200) {
                        var json = JSON.parse(body);
                        json.status = true;
                       return callback(null,json)
                    } else {
                        return callback(null,errBackMsg);
                    }
                });
            }//上传文件
            else if(req.body.__type == "import-video"){
                req.body.file = fs.createReadStream(req.files[req.body.filename].path);
                request.post({
                    url: config.domain+"/fileupload/uploadFile",
                    formData: req.body,
                    headers: httpHeader
                }, function optionalCallback(error, httpResponse, body) {
                    if (error) {
                        return callback(null,error);
                    }
                    if (!error && httpResponse.statusCode == 200) {
                        var json = JSON.parse(body);
                        json.status = true;
                       return callback(null,json)
                    } else {
                        return callback(null,errBackMsg);
                    }
                });
            }
            //上传图片
            else {
                var files = req.files[req.body.filename];
                //判断是单张传还是多张传
                var flag = Object.prototype.toString.call(files) === '[object Array]';
                //如果是单张,则数组化
                if (!flag) {
                    files = [];
                    files.push(req.files[req.body.filename]);
                }
                req.body.files = [];
                req.body.fileNames = [];
                for (var index = 0; index < files.length; index++) {
                    req.body.files[index] = fs.createReadStream(files[index].path);
                    req.body.fileNames[index] = files[index].name;
                }
                
                

                if (req.body.bucket === 'goodsimg') {
                    // console.log("********** cao");
                    // console.log(JSON.stringify(req.body.files, null, 4))
                    // console.log("********** cao");
                    request.post({
                        url: "http://upload.static.yohobuy.com",
                        formData: {
                            fileData: req.body.files,
                            project: req.body.bucket
                        }
                    }, function (error, httpResponse, rebody) {
                        if (!error && httpResponse.statusCode == 200) {
                            var ret = JSON.parse(rebody);
                            var imgs = ret.data.imagesList || [];
                            var datas = [];
                            for (var i = 0; i < imgs.length; i++) {
                                datas.push(Utils.joinImg(imgs[i]))
                            }
                            result = {
                                code: 200,
                                data: datas[0],
                                datas: datas,
                                names: req.body.fileNames,
                                message: '上传成功',
                                status: true
                            };
                        }
                        return callback(null, result);
                    });
                }else if (req.body.bucket === 'staticFile') {
                    req.body.file = fs.createReadStream(req.files[req.body.filename].path);
                    request.post({
                        url: config.domain + '/fileupload/uploadStaticFile',
                        formData: req.body
                    }, function optionalCallback(error, httpResponse, rebody) {
                        if (!error && httpResponse.statusCode == 200) {
                            result = JSON.parse(rebody);
                            result.status = true;
                        }
                        return callback(null, result);
                    });
                }else {
                    req.body.file = fs.createReadStream(req.files[req.body.filename].path);
                    request.post({
                        url: config.domain + '/fileupload/upload',
                        formData: req.body
                    }, function optionalCallback(error, httpResponse, rebody) {
                        if (!error && httpResponse.statusCode == 200) {
                            result = JSON.parse(rebody);
                            result.status = true;
                        }
                        return callback(null, result);
                    });
                }
            }
        },
        baiduUeditor: function (req, callback) {
            console.log("---------------baidu ueditor-------------");
            var result = {code: "500", message: "接口异常"};
            var httpHeader = Utils.createHttpHeader(req);
            if (!httpHeader) {
                result = {code: "501", message: "用户失效,请重新登录"};
                return callback(null, result);
            }

            var files = req.files.upfile;
            console.log(req.files);
            //判断是单张传还是多张传
            var flag = Object.prototype.toString.call(files) === '[object Array]';
            //如果是单张,则数组化
            if (!flag) {
                files = [];
                files.push(req.files.upfile);
            }

            req.body.files = [];
            req.body.fileNames = [];
            for (var index = 0; index < files.length; index++) {
                req.body.files[index] = fs.createReadStream(files[index].path);
                req.body.fileNames[index] = files[index].filename;
            }

            // req.body.files = [fs.createReadStream(req.files.upfile.path)];
            req.body.bucket = "goodsimg";
            request.post({
                url: "http://upload.static.yohobuy.com",
                formData: {
                    fileData: req.body.files,
                    project: req.body.bucket
                }
            }, function optionalCallback(error, httpResponse, body) {
                if (!error && httpResponse.statusCode == 200) {
                    var ret = JSON.parse(body);
                    console.log("--------" + body);
                    if (ret.code === 200) {
                        result = [];
                        for (var i = 0; i < ret.data.imagesList.length; i++) {
                            var imgUrl = ret.data.imagesList[i];
                            var rest = {};
                            imgUrl = Utils.joinImg(imgUrl);
                            if (imgUrl) {
                                rest.originalName = Date.now();
                                rest.name = Date.now();
                                rest.url = imgUrl;
                                rest.type = imgUrl.substring(imgUrl.lastIndexOf('.'));
                                rest.state = "SUCCESS";
                            } else {
                                rest.state = "FAIL";
                            }

                            result.push(rest);
                        }
                    }
                }
                return callback(null, result);
            });
        },
        downExcel: function (req, callback) {
            var result = request.get(config.domain + "/common/" + req.params.name + ".xlsx");
            return callback(null, result);
        },
        exportExcel: function (req, callback) {
            var httpHeader = Utils.createHttpHeader(req);
            var result = request({
                method: 'POST',
                url: config.domain + '/batch/export',
                headers:_.assign(httpHeader,{
                    'content-type': 'application/json'
                }),
                body: req.query,
                json: true
            });
            return callback(null, result);
        },
        proxy: function (req, callback) {
            var httpHeader = Utils.createHttpHeader(req);
            if (!httpHeader) {
                return null;
            }
            httpHeader['Content-Type'] = 'application/json';

            var result = request({
                headers: headers,
                url: global.config.domain + req.query.url,
                body: JSON.stringify(req.body)
            });
            return callback(null, result)
        },
        download: function (req, callback) {
            var result = request.get(config.domain + "/batch/download?path=" + req.query.path);
            return callback(null, result);
        }
    }
};