var uploadFile = function(fileKey){ ossClient = new ALY.OSS({ accessKeyId: option.accessKeyId, secretAccessKey: option.secretAccessKey, endpoint: option.endpoint, apiVersion: option.apiVersion }); ossClient.putObject({ Bucket: option.bucket, Key: fileKey, Body: file.contents, AccessControlAllowOrigin: '', CacheControl: 'no-cache', ContentDisposition: '', ContentEncoding: 'utf-8', ServerSideEncryption: 'AES256', Expires: Moment().unix() }, function (err, data) { if (err) { console.log('error:', err); log('ERR:', colors.red(fileKey + "\t" + err.code)); }else{ log('OK:', colors.green(fileKey)); } } ); };
fs.readFile(file.path, function (err, data) { if (err) { res.status(500).send(err); return; } var date = new Date(); var key = date.toLocaleDateString() + "/" + date.getTime() + file.originalFilename.substring(file.originalFilename.lastIndexOf('.')); oss.putObject({ Bucket: 'ismartjs', Key: key, Body: data, AccessControlAllowOrigin: '', CacheControl: 'no-cache', ContentDisposition: file.originalFilename, ContentEncoding: 'utf-8', ServerSideEncryption: 'AES256', Expires: null }, function (err, data) { if (err) { res.status(500).send(err); return; } res.send('"http://ismartjs.oss-cn-hangzhou.aliyuncs.com/' + key + '"'); }); });
function* test(){ oss.putObject({ Bucket: bucket, Key: fileKey, // 注意, Key 的值不能以 / 开头, 否则会返回错误. Body: buffer, AccessControlAllowOrigin: '', ContentType: ctype, // CacheControl: 'no-cache', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 // ContentDisposition: '', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 // ContentEncoding: 'utf-8', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 // ServerSideEncryption: 'AES256', // Expires: '' // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21 }, function (err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); return data }); }
it.skip('## should success getObject', function(done) { oss.getObject({ Bucket: options.Bucket, Key: options.Key //Range: '', //IfModifiedSince: '', //IfUnmodifiedSince: '', //IfMatch: '', //IfNoneMatch: '', //ResponseContentType: '', //ResponseContentLanguage: '', //ResponseExpires: '60', //ResponseCacheControl: '', //ResponseContentDisposition: '', //ResponseContentEncoding: '' }, function (err, data) { if (err) done(err); console.log('success:', data); done(); }); });
fs.readFile('test/fixtures/'+options.Key, function (err, data) { if (err) return done(err); oss.putObject({ Bucket: options.Bucket, Key: options.Key, // 注意, Key 的值不能以 / 开头, 否则会返回错误. Body: data, AccessControlAllowOrigin: '', ContentType: 'image/jpeg', CacheControl: 'no-cache', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 ContentDisposition: '', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 ContentEncoding: '', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 ServerSideEncryption: 'AES256' // Expires: '' // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21 }, function (err, data) { if (err) return done(err); console.log('success:', data); done(); }); });
fs.readFile(source, function (err, data) { if (err) { console.log('error:', err); return; } oss.putObject({ Bucket: process.env.Bucket, Key: dest, Body: data, AccessControlAllowOrigin: '', ContentType: contentType, CacheControl: 'no-cache', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 ContentDisposition: '', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 ContentEncoding: 'utf-8', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 ServerSideEncryption: 'AES256', Expires: (new Date()).getTime() + 3600 * 1000 // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21 }, function (err, data) { if (err) { console.log('error:', err); return; } console.log('success:', data); }); });
aliyun.uploadFile = function(fileInfo, cb){ var imageBuffer = decodeBase64Image(fileInfo.base64); if (!imageBuffer){ cb(new Error('转换失败')); return false; } oss.putObject({ Bucket: aliyun.config.bucket, Key: fileInfo.fileName, // 注意, Key 的值不能以 / 开头, 否则会返回错误. Body: imageBuffer.data, AccessControlAllowOrigin: '', ContentType: 'img/*', CacheControl: 'public', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 ContentDisposition: '', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 ContentEncoding: '', // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 ServerSideEncryption: '', Expires: new Date() // 参考: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21 }, function (err, data) { if (err) { cb(err); }else { cb(null, data); } }); };
fs.readFile(image.path,function(err,fileData){ if(err) return callback(new Error(err)); var hash = crypto.createHash('md5'), hex = hash.update(fileData+"").digest('hex'), dir = hex.slice(0,6), sub = hex.slice(6,12), name = hex.slice(12), ext = image.name.split('.')[image.name.split(".").length-1], parser = url.parse(NALY.config.domain), object_name = dir + '/' + sub + '/' + name + '.' + ext, oss_url = parser.protocol+ '//' + NALY.config.bucket + '.' + parser.host + '/' + object_name; oss.putObject({ Bucket : NALY.config.bucket, Key : object_name, Body : fileData, ContentType : 'image/' + ext },function(err,fileData){ if(err) { return callback(new Error(err)) } callback(null,{ url : oss_url, name : image.name }) }) });
module.exports = function (aws, options) { options = options || {}; if (!options.delay) { options.delay = 0; } var oss = new ALY.OSS({ accessKeyId: aws.key, secretAccessKey: aws.secret, endpoint: aws.endpoint, apiVersion: '2013-10-15' }); var regexGeneral = /\.([a-z]{2,})$/i; return es.mapSync(function (file) { // Verify this is a file if (!file.isBuffer()) { return file; } var uploadPath = file.path.replace(file.base, options.uploadPath || ''); uploadPath = uploadPath.replace(new RegExp('\\\\', 'g'), '/'); var headers = {}; if (options.headers) { for (var key in options.headers) { headers[key] = options.headers[key]; } } // Set content type based of file extension if (!headers['ContentType'] && regexGeneral.test(uploadPath)) { headers['ContentType'] = mime.lookup(uploadPath); } //headers['Content-Length'] = file.stat.size; headers['Body'] = file.contents; headers['Key'] = uploadPath; oss.putObject(headers, function (err, data) { if (err) { gutil.log(gutil.colors.red('[FAILED]', file.path + " -> " + uploadPath)); gutil.log(err); return; } gutil.log(gutil.colors.green('[SUCCESS]', file.path + " -> " + uploadPath)); }); return file; }); };
upload : function(image, callback) { image = image.image; if(!NALY.config.accessKeyId) { return callback(new Error('invalid-aliyun-oss-access-key-id')); } if(!NALY.config.secretAccessKey) { return callback(new Error('invalid-aliyun-oss-secret-access-key')); } if(!NALY.config.bucket) { return callback(new Error('invalid-aliyun-oss-bucket-name')) } if(!NALY.config.domain) { return callback(new Error('invalid-aliyun-oss-domain')) } if(!image || !image.path) { return callback(new Error('invalid image')); } var oss = new ALY.OSS({ accessKeyId:NALY.config.accessKeyId, secretAccessKey:NALY.config.secretAccessKey, endpoint: NALY.config.domain, apiVersion: '2013-10-15' }); fs.readFile(image.path,function(err,fileData){ if(err) return callback(new Error(err)); var hash = crypto.createHash('md5'), hex = hash.update(fileData+"").digest('hex'), dir = hex.slice(0,6), sub = hex.slice(6,12), name = hex.slice(12), ext = image.name.split('.')[image.name.split(".").length-1], parser = url.parse(NALY.config.domain), object_name = dir + '/' + sub + '/' + name + '.' + ext, oss_url = parser.protocol+ '//' + NALY.config.bucket + '.' + parser.host + '/' + object_name; oss.putObject({ Bucket : NALY.config.bucket, Key : object_name, Body : fileData, ContentType : 'image/' + ext },function(err,fileData){ if(err) { return callback(new Error(err)) } callback(null,{ url : oss_url, name : image.name }) }) }); },
it('## should success getSignedUrl', function(done) { var url = oss.getSignedUrl('getObject', { Bucket: options.Bucket, Key: options.Key, Expires: 60 }); console.log(url); done(); });
form.parse(req, function (err, fields, files) { "use strict"; var file = files.file[0]; if (file / 1024 > 500) { res.status(500).send("文件大小不能超过500K"); return; } if (!/^.+\.(gif|jpg|jpeg|png)$/gi.test(file.originalFilename)) { res.status(500).send("只能上传图片文件,允许的图片格式为:gif|jpg|jpeg|png"); return; } if (file / 1024 > 500) { res.status(500).send("文件大小不能超过500K"); return; } var oss = new ALI.OSS({ accessKeyId: "DGp93cpGeQD5axzf", secretAccessKey: "LbNDWEQrldzjlYvVjeLGZmRkWb6cGc", securityToken: "", endpoint: 'http://oss-cn-hangzhou.aliyuncs.com', apiVersion: '2013-10-15' }); var fs = require('fs'); fs.readFile(file.path, function (err, data) { if (err) { res.status(500).send(err); return; } var date = new Date(); var key = date.toLocaleDateString() + "/" + date.getTime() + file.originalFilename.substring(file.originalFilename.lastIndexOf('.')); oss.putObject({ Bucket: 'ismartjs', Key: key, Body: data, AccessControlAllowOrigin: '', CacheControl: 'no-cache', ContentDisposition: file.originalFilename, ContentEncoding: 'utf-8', ServerSideEncryption: 'AES256', Expires: null }, function (err, data) { if (err) { res.status(500).send(err); return; } res.send('"http://ismartjs.oss-cn-hangzhou.aliyuncs.com/' + key + '"'); }); }); });
return new Promise(function(resolve, reject){ oss.putObject({ Bucket: ossConfig.bucketname, Key: key, Body: data, Expires: 60 }, function (err, data) { if (err) { return reject(err); } return resolve(data); }); });
return es.mapSync(function (file) { // Verify this is a file if (!file.isBuffer()) { return file; } var uploadPath = file.path.replace(file.base, options.uploadPath || ''); uploadPath = uploadPath.replace(new RegExp('\\\\', 'g'), '/'); var headers = {}; if (options.headers) { for (var key in options.headers) { headers[key] = options.headers[key]; } } // Set content type based of file extension if (!headers['ContentType'] && regexGeneral.test(uploadPath)) { headers['ContentType'] = mime.lookup(uploadPath); } //headers['Content-Length'] = file.stat.size; headers['Body'] = file.contents; headers['Key'] = uploadPath; oss.putObject(headers, function (err, data) { if (err) { gutil.log(gutil.colors.red('[FAILED]', file.path + " -> " + uploadPath)); gutil.log(err); return; } gutil.log(gutil.colors.green('[SUCCESS]', file.path + " -> " + uploadPath)); }); return file; });
var os = require('os'); var fs = require('fs'); var events = require("events"); var emitter = new events.EventEmitter();//创建了事件监听器的一个对象 var oss = new ALY.OSS({ "accessKeyId": "", "secretAccessKey": "", // 根据你的 oss 实例所在地区选择填入 // 杭州:http://oss-cn-hangzhou.aliyuncs.com // 北京:http://oss-cn-beijing.aliyuncs.com // 青岛:http://oss-cn-qingdao.aliyuncs.com // 深圳:http://oss-cn-shenzhen.aliyuncs.com // 香港:http://oss-cn-hongkong.aliyuncs.com // 注意:如果你是在 ECS 上连接 OSS,可以使用内网地址,速度快,没有带宽限制。 // 杭州:http://oss-cn-hangzhou-internal.aliyuncs.com // 北京:http://oss-cn-beijing-internal.aliyuncs.com // 青岛:http://oss-cn-qingdao-internal.aliyuncs.com // 深圳:http://oss-cn-shenzhen-internal.aliyuncs.com // 香港:http://oss-cn-hongkong-internal.aliyuncs.com endpoint: 'http://oss-cn-shenzhen.aliyuncs.com' , //'http://oss.atsmart.io', // 这是 oss sdk 目前支持最新的 api 版本, 不需要修改 apiVersion: '2013-10-15' }); var Bucket = 'atsmart-oss'; var filepath = "test.png"; console.log("try to upload :" + filepath) /*
//ali 图片上传 function mup(buffer,fileKey,bucket){ // File // var fileName = 'test.mp3'; // var filePath = './' + fileName; // var fileKey = fileName; // var buffer = fs.readFileSync(filePath); // Upload options // Upload var startTime = new Date(); var partNum = 0; var partSize = 1024 * 1024 * 5; // Minimum 5MB per chunk (except the last part) var numPartsLeft = Math.ceil(buffer.length / partSize); var maxUploadTries = 3; var multipartMap = { Parts: [] }; function completeMultipartUpload(oss, doneParams) { oss.completeMultipartUpload(doneParams, function (err, data) { if (err) { console.log("An error occurred while completing the multipart upload"); console.log(err); } else { var delta = (new Date() - startTime) / 1000; console.log('Completed upload in', delta, 'seconds'); console.log('Final upload data:', data); } }); } function uploadPart(oss, multipart, partParams, tryNum) { var tryNum = tryNum || 1; oss.uploadPart(partParams, function (multiErr, mData) { if (multiErr) { console.log('multiErr, upload part error:', multiErr); if (tryNum < maxUploadTries) { console.log('Retrying upload of part: #', partParams.PartNumber) uploadPart(oss, multipart, partParams, tryNum + 1); } else { console.log('Failed uploading part: #', partParams.PartNumber) } return; } multipartMap.Parts[this.request.params.PartNumber - 1] = { ETag: mData.ETag, PartNumber: Number(this.request.params.PartNumber) }; console.log("Completed part", this.request.params.PartNumber); console.log('mData', mData); if (--numPartsLeft > 0) return; // complete only when all parts uploaded var doneParams = { Bucket: bucket, Key: fileKey, CompleteMultipartUpload: multipartMap, UploadId: multipart.UploadId }; console.log("Completing upload..."); completeMultipartUpload(oss, doneParams); }); } // Multipart console.log("Creating multipart upload for:", fileKey); oss.createMultipartUpload({ ACL: 'public-read', Bucket: bucket, Key: fileKey, ContentType: 'audio/mpeg', ContentDisposition: '' //CacheControl: '', //ContentEncoding: '', //Expires: '', //ServerSideEncryption: '' }, function (mpErr, multipart) { if (mpErr) { console.log('Error!', mpErr); return; } console.log("Got upload ID", multipart.UploadId); // Grab each partSize chunk and upload it as a part for (var rangeStart = 0; rangeStart < buffer.length; rangeStart += partSize) { partNum++; var end = Math.min(rangeStart + partSize, buffer.length), partParams = { Body: buffer.slice(rangeStart, end), Bucket: bucket, Key: fileKey, PartNumber: String(partNum), UploadId: multipart.UploadId }; // Send a single part console.log('Uploading part: #', partParams.PartNumber, ', Range start:', rangeStart); uploadPart(oss, multipart, partParams); } }); }
function *aliService(path2save){ if (!this.request.is('multipart/*')) return yield next var oss = require('ali-oss') var store = oss({ accessKeyId: 'e9lpoiqUPkmNrupH', accessKeySecret: 'II8SFBfkQXzWheLyB3GQulzgYYzd7d', bucket: 'jh-ljs-account', region: 'oss-cn-shenzhen' }); var stat = false; var object; var part; var filename; var buffers = []; var nread = 0; var bucket = 'jh-ljs-account'; var parts = parse(this, { // only allow upload `.jpg` files checkFile: function (fieldname, file, filename) { if(_.indexOf(filterPicture,path.extname(filename))===-1){ var err = new Error('invalid jpg image') err.status = 400 return err; } } }) while (part = yield parts) { if (part.length) { // arrays are busboy fields console.log('key: ' + part[0]) console.log('value: ' + part[1]) if(part[0]==='name'){ filename = part[1]; var names = filename.split("&&&"); if (names[0] === 'goods'){ bucket = 'jh-ljs-goods'; filename = names[1]; } } if(part[0]==='type'){ ctype = part[1]; } if(part[0]==='size'){ csize = part[1]; } } else{ var object = yield store.put(filename, part, { headers: { 'Content-Length': csize, 'Content-Type': ctype } }); } } if(object) this.body = { "state": "SUCCESS", "url": "upload/demo.jpg", "title": "demo.jpg", "original": "demo.jpg", success: true, message: filename } else { this.body = {"state": "failed", success: false} } // if (!this.request.is('multipart/*')) return yield next // // var stat = false; // var part; // var filename; // var buffers = []; // var nread = 0; // var bucket = 'jh-ljs-account'; // // var parts = parse(this, { // // only allow upload `.jpg` files // checkFile: function (fieldname, file, filename) { // if(_.indexOf(filterPicture,path.extname(filename))===-1){ // var err = new Error('invalid jpg image') // err.status = 400 // return err; // } // } // }) // // while (part = yield parts) { // if (part.length) { // // arrays are busboy fields // console.log('key: ' + part[0]) // console.log('value: ' + part[1]) // if(part[0]==='name'){ // filename = part[1]; // var names = filename.split("&&&"); // if (names[0] === 'goods'){ // bucket = 'jh-ljs-goods'; // filename = names[1]; // } // } // if(part[0]==='type'){ // ctype = part[1]; // } // } // else { // // if(filename){ // // var ext = path.extname(filename); // // filename = lib.guid()+ext // // // filename = path.join(path2save,filename); // // } // // // // else{ // // return false; // // } // // part.on('data', function (chunk) { // buffers.push(chunk); // nread += chunk.length; // }); // // part.on('end', function () { // stat = true; // // switch(buffers.length) { // case 0: // buffer = new Buffer(0); // break; // case 1: // buffer = buffers[0]; // break; // default: // buffer = new Buffer(nread); // for (var i = 0, pos = 0, l = buffers.length; i < l; i++) { // var chunk = buffers[i]; // chunk.copy(buffer, pos); // pos += chunk.length; // } // break; // } // objup(buffer,filename,bucket); // // mup(buffer,filename,bucket); // console.log('push picture to aliyun') // }); // } // } // // yield buffer // if(stat) // this.body = {success: true}; // else // this.body = {success: false}; }