Exemplo n.º 1
0
function qiuniuUploadToken(key) {
    var qiniu = require("node-qiniu");

//需要填写你的 Access Key 和 Secret Key
    qiniu.config({
        access_key: confige.qiniu.accesskey,
        secret_key: confige.qiniu.secretkey
    });

//要上传的空间
    var bucket = qiniu.bucket(confige.qiniu.fileSpace);

    var asset = bucket.key(key);
}
Exemplo n.º 2
0
function qiniuPutStream(filename) {
    var qiniu = require("node-qiniu");

//需要填写你的 Access Key 和 Secret Key
    qiniu.config({
        access_key: confige.qiniu.accesskey,
        secret_key: confige.qiniu.secretkey
    });

//要上传的空间
    var imagesBucket = qiniu.bucket(confige.qiniu.fileSpace);

    return imagesBucket.createPutStream(filename);


}
Exemplo n.º 3
0
function qiniuImageDelete(image) {
    if (!image) return;
    var qiniu = require("node-qiniu");

//需要填写你的 Access Key 和 Secret Key
    qiniu.config({
        access_key: confige.qiniu.accesskey,
        secret_key: confige.qiniu.secretkey
    });

//要上传的空间
    var imagesBucket = qiniu.bucket(confige.qiniu.fileSpace);
    imagesBucket.key(image).remove(function (err) {
        if (err) {
            logger.errno(err);
        } else {
            logger.info('七牛资源删除成功:' + image);
        }
    });
}
Exemplo n.º 4
0
module.exports = function(setting, option, deferred) {
    option = option || {};
    option = extend({
        dir: ''
    }, option);

    qiniu.config({
        access_key: setting.accessKey,
        secret_key: setting.secretKey
    });

    var bucket = qiniu.bucket(setting.bucket);

    var qs = [];
    var errorFiles = [];
    var filesNo = 0;

    function detective(file, fileKey) {
        var localHashDefer = Q.defer();
        var remoteHashDefer = Q.defer();

        getEtag(file.contents, function(hash) {
            localHashDefer.resolve(hash);
        });

        var assert = bucket.key(fileKey);

        assert.stat(function(err, stat) {
            if (err) {
                console.log(('\n七牛内部错误 → stat:' + JSON.stringify(err)).red);
                return remoteHashDefer.reject('network_error');
            }
            remoteHashDefer.resolve(stat.hash);
        });

        return Q.all([localHashDefer.promise, remoteHashDefer.promise])
            .then(function(result) {
                if (result[0] == undefined) {
                    return Q.reject('error');
                }
                if (result[1] == undefined) {
                    return Q.resolve('upload');
                }
                if (result[0] == result[1]) {
                    return Q.resolve('keep');
                } else {
                    return Q.reject('different');
                }
            });
    }

    function uploadFiles(files) {
        var failQs = []
        var qs = files.map(function(item) {
            return function() {
                return bucket.putFile(item.fileKey, item.file.path)
                    .then(function() {
                        log('上传七牛完毕', colors.green(item.file.path), '→', colors.green(item.fileKey));
                    }, function() {
                        failQs.push(item);
                        log('上传七牛失败', colors.red(item.file.path), '→', colors.red(item.fileKey));
                        console.log(('\n上传七牛失败 → ' + item.file.path).red);
                    });
            };
        });

        if (qs.length) {
            return throat(qs, PARALLEL)
                .then(function() {
                    if (failQs.length) {
                        console.log('开始重传', failQs.length, '个文件');
                        return uploadFiles(failQs);
                    }
                });
        } else {
            return [];
        }

    }

    var countKeep = 0;
    var countUpload = 0;
    return through2.obj(function(file, enc, next) {
        var that = this;
        if (file._contents === null) return next();

        var filePath = path.relative(file.base, file.path);
        var fileKey = option.dir + ((!option.dir || option.dir[option.dir.length - 1]) === '/' ? '' : '/') +
            filePath;

        qs.push(function() {
            return detective(file, fileKey)
                .then(function(action) {
                    if (action == 'upload') {
                        countUpload++;
                    } else {
                        countKeep++;
                    }
                    if (process.stdin.isTTY) {
                        process.stdout.clearLine();
                        process.stdout.cursorTo(0);
                        process.stdout.write('相同: ' + countKeep + '\t需要上传: ' + countUpload +
                            '\t错误:' + errorFiles.length);
                    }

                    if (action == 'upload') {
                        return {
                            file: file,
                            fileKey: fileKey
                        };
                    }
                })
                .fail(function(e) {
                    errorFiles.push({
                        fileKey: fileKey,
                        error: e
                    });
                });
        });

        next();
    }, function(next) {

        throat(qs, PARALLEL)
            .then(function(result) {
                if (process.stdin.isTTY) {
                    process.stdout.write('\n');
                }
                errorFiles.forEach(function(item) {
                    log(colors.red(item.error), item.fileKey);
                });
                result = result.filter(function(item) {
                    return item != undefined;
                });
                return uploadFiles(result);
            })
            .then(deferred && deferred.resolve)
            .fail(function(reason) {
                dumpError(reason);
            });
    });
}
Exemplo n.º 5
0
var http = require('http');
var qiniu = require('node-qiniu');
var fs = require('fs');
var util = require('util');

qiniu.config({
  access_key: 'T0lz0dQPnAeANGo3jaIAa4hx8pIS5D7uxxNx_Jr5',
  secret_key: '1GhmeedXAtJ7r9A6Cg_Vc2VpcppIczvytKgOjrrC'
});

var uploadPage = fs.readFileSync(__dirname + '/index.html').toString();
var viewPage = fs.readFileSync(__dirname + '/view.html').toString();
var qiniuJs = fs.readFileSync(__dirname + '/../dist/qiniu.js');

var bucket = qiniu.bucket('iwillwen');

var server = http.createServer(function(req, res) {
  switch (req.url) {
    case '/':
      var putToken = bucket.token();

      res.end(util.format(uploadPage, putToken));
      break;

    case '/token':
      var putToken = bucket.token()

      res.writeHead(200, {
        'Content-Type': 'application/json'
      })
      res.end(JSON.stringify({
Exemplo n.º 6
0
function Config (app) {
    // log("Attempt to load from config.json")
    try {
        config = require('./config.json');
        log('Loaded from config.json %j', config);
    } catch (err) {
        log("Failed to load file config.json %j", err);
    }

    // log('Attemp to load from environment');
    utils.merge(config, env);

    // log('Save configuration values in app %j', config);
    app.set('config', config);

    // log('Setting port as %d', config.app.port);
    app.set('port', config.app.port);

    // log('Setting view engine as %s', 'jade');
    app.set('view engine', 'jade');

// mysql
// ==========
    app.set('mysqlConf', config.mysqlConf);

    var mysqlConfig = config.mysqlConf;

    var mysqlClient = require('mysql').createConnection(mysqlConfig);

    app.set('mysqlClient', mysqlClient);

    console.log('====== Connected to MySQL automatically ======');


// qiniu
// ==========

    // node qiniu
    nodeQiniu.config({
        access_key: config.qiniuConfig.access_key,
        secret_key: config.qiniuConfig.secret_key
    });
    var imagesBucket = nodeQiniu.bucket(config.qiniuConfig.bucket_name);

    app.set('imagesBucket', imagesBucket);

    // qiniu
    qiniu.conf.ACCESS_KEY = config.qiniuConfig.access_key
    qiniu.conf.SECRET_KEY = config.qiniuConfig.secret_key


// redis
// ==========
    // log('Setting redisURL', config.redisURL);
    app.set('redisURL', config.redisURL);

    // log('Opening a redis mysql connection');
    // This should be moved to a db.js module
    var redisConfig = url.parse(config.redisURL);
    var redisClient = redis.createClient(redisConfig.port, redisConfig.hostname);
  
    redisClient.on('error', function(err) {
        console.log('Error connecting to redis %j', err);
    }).on('connect', function() {
        console.log('====== Connected to redis. ======');
    }).on('ready', function() {
        console.log('====== Redis mysql ready. ======');
    });

    if (redisConfig.auth) {
        // auth 1st part is username and 2nd is password separated by ":"
        redisClient.auth(redisConfig.auth.split(':')[1]);
    };

    // log('Saving redisClient connection in app');
    app.set('redisClient', redisClient);

    // log('Creating and saving a session store instance with redis mysql.');
    app.set('sessionStore', new RedisStore({mysql: redisClient}));




    // log('Setting views lookup root path.');
    app.set('views', path.join(__dirname, '..', '/views/themes/', config.theme.name));

    // log('Setting static files lookup root path.');
    app.use(express.static(path.join(__dirname, '..', '/public')));

    if(config.debug === true) {
        console.log('====== express debug enabled ======');
        app.use(express.logger('dev'));
    }

    // log('Use of express body parser middleware.');
    app.use(express.bodyParser());

    // log('Use of express cookie parser middleware.');
    app.use(express.cookieParser(config.session.secret));

    // log('Use of express session middleware.');
    app.use(express.session({
        key: config.session.key,
        store: app.get('sessionStore')
    }));
  
    // log('Use of passport middlewares.');
    app.use(passport.initialize());
    app.use(passport.session());

    // log('Use of express router.');
    app.use(app.router);
}