aliyun OSS(object storage service) Node.js client.
npm install ali-oss --save
OSS, Object Storage Service. Equal to well known Amazon S3.
| region | country | city | endpoint | internal endpoint |
|---|---|---|---|---|
| oss-cn-hangzhou | China | HangZhou | oss-cn-hangzhou.aliyuncs.com | oss-cn-hangzhou-internal.aliyuncs.com |
| oss-cn-shanghai | China | ShangHai | oss-cn-shanghai.aliyuncs.com | oss-cn-shanghai-internal.aliyuncs.com |
| oss-cn-qingdao | China | QingDao | oss-cn-qingdao.aliyuncs.com | oss-cn-qingdao-internal.aliyuncs.com |
| oss-cn-beijing | China | BeiJing | oss-cn-beijing.aliyuncs.com | oss-cn-beijing-internal.aliyuncs.com |
| oss-cn-shenzhen | China | ShenZhen | oss-cn-shenzhen.aliyuncs.com | oss-cn-shenzhen-internal.aliyuncs.com |
| oss-cn-hongkong | China | HongKong | oss-cn-hongkong.aliyuncs.com | oss-cn-hongkong-internal.aliyuncs.com |
| oss-us-west-1 | US | Silicon Valley | oss-us-west-1.aliyuncs.com | oss-us-west-1-internal.aliyuncs.com |
| oss-ap-southeast-1 | Singapore | Singapore | oss-ap-southeast-1.aliyuncs.com | oss-ap-southeast-1-internal.aliyuncs.com |
Go to OSS website, create a new account for new user.
After account created, you can create the OSS instance and get the accessKeyId and accessKeySecret.
Each OSS instance required accessKeyId, accessKeySecret and bucket.
Create a Bucket store instance.
options:
putBucket() create one first.region.oss-cn-hangzhou.false.
If your servers are running on aliyun too, you can set true to save lot of money.60sexample:
var oss = require('ali-oss');
var store = oss({
accessKeyId: 'your access key',
accessKeySecret: 'your access secret',
bucket: 'your bucket name',
region: 'oss-cn-hangzhou'
});
List buckets in this account.
parameters:
null
prefix keymarker, including marker key100, limit to 1000Success will return buckets list on buckets properties.
BucketMeta will contains blow properties:
oss-cn-hangzhou-a2015-02-19T08:39:44.000Zid and displayNameexample:
var result = yield store.listBuckets({
"max-keys": 10
});
console.log(result);
Create a new bucket.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhen
If change exists bucket region, will throw BucketAlreadyExistsError.
If region value invalid, will throw InvalidLocationConstraintError.Success will return the bucket name on bucket properties.
example:
helloworld location on HongKongyield store.putBucket('helloworld', 'oss-cn-hongkong');
// use it by default
store.useBucket('helloworld', 'oss-cn-hongkong');
Delete an empty bucket.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
example:
yield store.deleteBucket('helloworld', {
region: 'oss-cn-hongkong'
});
Use the bucket.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenexample:
helloworld as the default bucketstore.useBucket('helloworld', 'oss-cn-hongkong');
Update the bucket ACL.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenpublic-read-write, public-read and privateSuccess will return:
example:
helloworld to public-read-writeyield store.putBucketACL('helloworld', 'oss-cn-hongkong', 'public-read-write');
Get the bucket ACL.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
example:
helloworldvar result = yield store.getBucketACL('helloworld', 'oss-cn-hongkong');
console.log(result.acl);
Update the bucket logging settings.
Log file will create every one hour and name format: <prefix><bucket>-YYYY-mm-DD-HH-MM-SS-UniqueString.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
example:
helloworld logging and save with prefix logs/yield store.putBucketLogging('helloworld', 'oss-cn-hongkong', 'logs/');
Get the bucket logging settings.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
nullexample:
helloworld logging settingsvar result = yield store.getBucketLogging('helloworld', 'oss-cn-hongkong');
console.log(result.enable, result.prefix);
Delete the bucket logging settings.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
Set the bucket as a static website.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenindex.htmlSuccess will return:
example:
yield store.putBucketWebsite('hello', 'oss-cn-hangzhou', {
index: 'index.html'
});
Get the bucket website config.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
nullDelete the bucket website config.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
Set the bucket request Referer white list.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenreferers {Array} Referer white list, e.g.:
[
'https://npm.taobao.org',
'http://cnpmjs.org'
]
Success will return:
example:
yield store.putBucketReferer('hello', 'oss-cn-hangzhou', false, [
'https://npm.taobao.org',
'http://cnpmjs.org'
]);
Get the bucket request Referer white list.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
Referer white list
Delete the bucket request Referer white list.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
Set the bucket object lifecycle.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenRule will contains blow properties:
Enabled or Disableddays2022-10-11T00:00:00.000Z
date and days only set one.Success will return:
example:
yield store.putBucketLifecycle('hello', 'oss-cn-hangzhou', [
{
id: 'delete after one day',
prefix: 'logs/',
status: 'Enabled',
days: 1
},
{
prefix: 'logs2/',
status: 'Disabled',
date: '2022-10-11T00:00:00.000Z'
}
]);
Get the bucket object lifecycle.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
Delete the bucket object lifecycle.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
Set CORS rules of the bucket object
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenRule will contains below properties:
Success will return:
example:
yield store.putBucketCORS('hello', 'oss-cn-hangzhou', [
{
allowedOrigin: '*',
allowedMethod: [
'GET',
'HEAD',
],
}
]);
Get CORS rules of the bucket object.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
Delete CORS rules of the bucket object.
parameters:
oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenSuccess will return:
All operations function is generator, except signatureUrl.
generator function format: functionName*(...).
Add an object to the bucket.
parameters:
x-oss-meta- prefix string
e.g.: { uid: 123, pid: 110 }Cache-Control: public, no-cacheContent-Disposition: somenameContent-Encoding: gzipExpires: 3600000Success will return the object information.
object:
example:
var filepath = '/home/ossdemo/demo.txt';
var object = yield store.put('ossdemo/demo.txt', filepath);
console.log(object);
{
name: 'ossdemo/demo.txt',
res: {
status: 200,
headers: {
date: 'Tue, 17 Feb 2015 13:28:17 GMT',
'content-length': '0',
connection: 'close',
etag: '"BF7A03DA01440845BC5D487B369BC168"',
server: 'AliyunOSS',
'x-oss-request-id': '54E341F1707AA0275E829244'
},
size: 0,
rt: 92
}
}
var object = yield store.put('ossdemo/buffer', new Buffer('foo content'));
console.log(object);
{
name: 'ossdemo/buffer',
url: 'http://demo.oss-cn-hangzhou.aliyuncs.com/ossdemo/buffer',
res: {
status: 200,
headers: {
date: 'Tue, 17 Feb 2015 13:28:17 GMT',
'content-length': '0',
connection: 'close',
etag: '"xxx"',
server: 'AliyunOSS',
'x-oss-request-id': '54E341F1707AA0275E829243'
},
size: 0,
rt: 92
}
}
var filepath = '/home/ossdemo/demo.txt';
var object = yield store.put('ossdemo/readstream.txt', fs.createReadStream(filepath));
console.log(object);
{
name: 'ossdemo/readstream.txt',
url: 'http://demo.oss-cn-hangzhou.aliyuncs.com/ossdemo/readstream.txt',
res: {
status: 200,
headers: {
date: 'Tue, 17 Feb 2015 13:28:17 GMT',
'content-length': '0',
connection: 'close',
etag: '"BF7A03DA01440845BC5D487B369BC168"',
server: 'AliyunOSS',
'x-oss-request-id': '54E341F1707AA0275E829242'
},
size: 0,
rt: 92
}
}
Add a stream object to the bucket.
parameters:
chunked encoding will be used if absentx-oss-meta- prefix string
e.g.: { uid: 123, pid: 110 }Cache-Control: public, no-cacheContent-Disposition: somenameContent-Encoding: gzipExpires: 3600000Success will return the object information.
object:
example:
var filepath = '/home/ossdemo/demo.txt';
var object = yield store.put('ossdemo/readstream.txt', fs.createReadStream(filepath));
console.log(object);
{
name: 'ossdemo/readstream.txt',
url: 'http://demo.oss-cn-hangzhou.aliyuncs.com/ossdemo/readstream.txt',
res: {
status: 200,
headers: {
date: 'Tue, 17 Feb 2015 13:28:17 GMT',
'content-length': '0',
connection: 'close',
etag: '"BF7A03DA01440845BC5D487B369BC168"',
server: 'AliyunOSS',
'x-oss-request-id': '54E341F1707AA0275E829242'
},
size: 0,
rt: 92
}
}
Append an object to the bucket, it's almost same as put, but it can add content to existing object rather than override it.
All parameters are same as put except for options.position
x-oss-meta- prefix string
e.g.: { uid: 123, pid: 110 }Cache-Control: public, no-cacheContent-Disposition: somenameContent-Encoding: gzipExpires: 3600000object:
example:
var object = yield store.apend('ossdemo/buffer', new Buffer('foo'));
// append content to the existing object
object = yield store.apend('ossdemo/buffer', new Buffer('bar'), {
position: object.nextAppendPosition,
});
Get the Object url.
If provide baseUrl, will use baseUrl instead the default endpoint.
e.g.:
const cdnUrl = client.getObjectUrl('foo/bar.jpg', 'https://mycdn.domian.com');
// cdnUrl should be `https://mycdn.domian.com/foo/bar.jpg`
Head an object and get the meta info.
parameters:
Success will return the object's meta information.
object:
put(), will return null.
If return status 304, meta will be null tooexample:
yield this.store.put('ossdemo/head-meta', new Buffer('foo'), {
meta: {
uid: 1,
path: 'foo/demo.txt'
}
});
var object = this.store.head('ossdemo/head-meta');
console.log(object);
{
status: 200,
meta: {
uid: '1',
path: 'foo/demo.txt'
},
res: { ... }
}
var object = this.store.head('ossdemo/head-meta');
// will throw NoSuchKeyError
Get an object from the bucket.
parameters:
file is null or ignore this parameter, function will return info contains content property.x-oss-process
e.g.: {process: 'image/resize,w_200'}Range: bytes=0-9Success will return the info contains response.
object:
file parameter is null or ignoreIf object not exists, will throw NoSuchKeyError.
example:
var filepath = '/home/ossdemo/demo.txt';
yield store.get('ossdemo/demo.txt', filepath);
_ Store object to a writestream
yield store.get('ossdemo/demo.txt', somestream);
var result = yield store.get('ossdemo/demo.txt');
console.log(Buffer.isBuffer(result.content));
var filepath = '/home/ossdemo/demo.png';
yield store.get('ossdemo/demo.png', filepath, {process: 'image/resize,w_200'});
var filepath = '/home/ossdemo/demo.txt';
yield store.get('ossdemo/not-exists-demo.txt', filepath);
// will throw NoSuchKeyError
Get an object read stream.
parameters:
x-oss-processSuccess will return the stream instance and response info.
object:
null.If object not exists, will throw NoSuchKeyError.
example:
var result = yield store.getStream('ossdemo/demo.txt');
result.stream.pipe(fs.createWriteStream('some file.txt'));
Delete an object from the bucket.
parameters:
Success will return the info contains response.
object:
If delete object not exists, will also delete success.
example:
yield store.delete('ossdemo/someobject');
yield store.delete('ossdemo/some-not-exists-object');
Copy an object from sourceName to name.
parameters:
sourceName start with /, meaning it's a full name contains the bucket name.
e.g.: /otherbucket/logo.png meaning copy otherbucket logn.png object to current bucket.x-oss-meta- prefix string
e.g.: { uid: 123, pid: 110 }
If the meta set, will override the source object meta.Success will return the copy result in data property.
object:
", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"If source object not exists, will throw NoSuchKeyError.
example:
var result = yield store.copy('newName', 'oldName');
var result = yield store.copy('logo.png', '/other-bucket/logo.png');
Set an exists object meta.
parameters:
x-oss-meta- prefix string
e.g.: { uid: 123, pid: 110 }
If meta: null, will clean up the exists metaSuccess will return the copy result in data property.
2015-02-19T08:39:44.000Z", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"If object not exists, will throw NoSuchKeyError.
example:
var result = yield store.putMeta('ossdemo.txt', {
uid: 1, pid: 'p123'
});
console.log(result);
yield store.putMeta('ossdemo.txt', null);
Delete multi objects in one request.
parameters:
false, verbose mode
quiet mode: if all objects delete succes, return emtpy response.
otherwise return delete error object results.
verbose mode: return all object delete results.Success will return delete success objects in deleted property.
example:
var result = yield store.deleteMulti(['obj1', 'obj2', 'obj3'], {
quiet: true
});
var result = yield store.deleteMulti(['obj1', 'obj2', 'obj3']);
List objects in the bucket.
parameters:
null
prefix keymarker, including marker key/ only search current dir, not including subdir100, limit to 1000Success will return objects list on objects properties.
ObjectMeta will contains blow properties:
2015-02-19T08:39:44.000Z", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"Normal344606Standardid and displayNameexample:
var result = yield store.list();
console.log(result.objects);
fun/ dir including subdirs objectsvar result = yield store.list({
prefix: 'fun/'
});
console.log(result.objects);
fun/ dir objects, not including subdirsvar result = yield store.list({
prefix: 'fun/',
delimiter: '/'
});
console.log(result.objects);
Create a signature url for download or upload object.
parameters:
1800x-oss-process
e.g.: {process: 'image/resize,w_200'}Success will return signature url.
example:
var url = store.signatureUrl('ossdemo.txt');
console.log(url);
var url = store.signatureUrl('ossdemo.txt', {
expires: 3600,
method: 'PUT'
});
console.log(url);
var url = store.signatureUrl('ossdemo.txt', {
expires: 3600,
response: {
'content-type': 'text/custom',
'content-disposition': 'attachment'
}
});
console.log(url);
var url = store.signatureUrl('ossdemo.png', {
process: 'image/resize,w_200'
});
console.log(url);
var url = store.signatureUrl('ossdemo.png', {
expires: 3600,
process: 'image/resize,w_200'
});
console.log(url);
Set object's ACL.
parameters:
Success will return:
example:
yield store.putACL('ossdemo.txt', 'public-read');
Get object's ACL.
parameters:
Success will return:
example:
var result = yield store.getACL('ossdemo.txt');
console.log(result.acl);
Upload file with OSS multipart.
parameters:
Cache-Control: public, no-cacheContent-Disposition: somenameContent-Encoding: gzipExpires: 3600000Success will return:
example:
var result = yield store.multipartUpload('object', '/tmp/file');
console.log(result);
var result = yield store.multipartUpload('object', '/tmp/file', {
parallel: 4,
partSize: 1024 * 1024,
progress: function* (p, cpt, res) {
console.log(p);
console.log(cpt);
console.log(res.headers['x-oss-request-id']);
}
});
var result = yield store.multipartUpload('object', '/tmp/file', {
checkpoint: savedCpt,
progress: function* (p, cpt, res) {
console.log(p);
console.log(cpt);
console.log(res.headers['x-oss-request-id']);
}
});
List on-going multipart uploads, i.e.: those not completed and not aborted.
parameters:
upload-id-marker
is not provided, return uploads with key > marker, otherwise
return uploads with key >= marker && uploadId > id-markerkey-markerexample:
var result = yield store.listUploads({
'max-uploads': 100,
'key-marker': 'my-object',
'upload-id-marker': 'upload-id'
});
console.log(result);
Abort a multipart upload for object.
parameters:
example:
var result = yield store.abortMultipartUpload('object', 'upload-id');
console.log(result);
Each Image Service instance required accessKeyId, accessKeySecret, bucket and imageHost.
Create a Image service instance.
options:
putBucket() create one first.oss-cn-hangzhou
Current available: oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhenfalse
If your servers are running on aliyun too, you can set true to save lot of money.60sexample:
var oss = require('ali-oss');
var imgClient = oss.ImageClient({
accessKeyId: 'your access key',
accessKeySecret: 'your access secret',
bucket: 'my_image_bucket'
imageHost: 'thumbnail.myimageservice.com'
});
All operations function is generator, except imgClient.signatureUrl.
generator function format: functionName*(...).
Get an image from the image channel.
parameters:
file is null or ignore this parameter, function will return info contains content property.Success will return the info contains response.
object:
file parameter is null or ignoreIf object not exists, will throw NoSuchKeyError.
example:
var imagepath = '/home/ossdemo/demo.jpg';
yield imgClient.get('ossdemo/demo.jpg@200w_200h', filepath);
_ Store image to a writestream
yield imgClient.get('ossdemo/demo.jpg@200w_200h', somestream);
var result = yield imgClient.get('ossdemo/demo.jpg@200w_200h');
console.log(Buffer.isBuffer(result.content));
var imagepath = '/home/ossdemo/demo.jpg';
yield imgClient.get('ossdemo/not-exists-demo.jpg@200w_200h', filepath);
// will throw NoSuchKeyError
Get an image read stream.
parameters:
Success will return the stream instance and response info.
object:
null.If object not exists, will throw NoSuchKeyError.
example:
var result = yield imgClient.getStream('ossdemo/demo.jpg@200w_200h');
result.stream.pipe(fs.createWriteStream('some demo.jpg'));
Get a image exif info by image object name from the image channel.
parameters:
Success will return the info contains response.
object:
If object don't have exif, will throw 400 BadRequest.
example:
var result = yield imgClient.getExif('demo.jpg');
// resut:
// {
// res: {
// status: 200,
// statusCode: 200,
// headers: {
// server: "Tengine",
// content - type: "application/json",
// content - length: "148",
// connection: "keep-alive",
// date: "Tue, 31 Mar 2015 11:06:32 GMT",
// "last-modified": "Mon, 30 Mar 2015 10:46:35 GMT"
// },
// size: 148,
// aborted: false,
// rt: 461,
// keepAliveSocket: false
// },
// data: {
// FileSize: 343683,
// ImageHeight: 1200,
// ImageWidth: 1600,
// Orientation: 1
// }
// }
Get a image info and exif info by image object name from the image channel.
parameters:
Success will return the info contains response.
object:
example:
var result = yield imgClient.getInfo('demo.jpg');
// resut:
// {
// res: {
// status: 200,
// statusCode: 200,
// headers: {
// server: "Tengine",
// content - type: "application/json",
// content - length: "148",
// connection: "keep-alive",
// date: "Tue, 31 Mar 2015 11:06:32 GMT",
// "last-modified": "Mon, 30 Mar 2015 10:46:35 GMT"
// },
// size: 148,
// aborted: false,
// rt: 461,
// keepAliveSocket: false
// },
// data: {
// FileSize: 343683,
// Format: "jpg",
// ImageHeight: 1200,
// ImageWidth: 1600,
// Orientation: 1
// }
// }
// TODO
Get a style by name from the image channel.
parameters:
Success will return the info contains response.
object:
example:
var result = yield imgClient.getStyle('400');
// resut:
// {
// res: {
// status: 200,
// statusCode: 200,
// headers: {
// server: "Tengine",
// content - type: "application/xml",
// content - length: "234",
// connection: "keep-alive",
// date: "Tue, 31 Mar 2015 10:58:20 GMT"
// },
// size: 234,
// aborted: false,
// rt: 398,
// keepAliveSocket: false
// },
// data: {
// Name: "400",
// Content: "400w_90Q_1x.jpg",
// CreateTime: "Thu, 19 Mar 2015 08:34:21 GMT",
// LastModifyTime: "Thu, 19 Mar 2015 08:34:21 GMT"
// }
// }
Get all styles from the image channel.
parameters:
Success will return the info contains response.
object:
example:
var result = yield imgClient.listStyle();
// resut:
// {
// res: {
// status: 200,
// statusCode: 200,
// headers: {
// server: "Tengine",
// content - type: "application/xml",
// content - length: "913",
// connection: "keep-alive",
// date: "Tue, 31 Mar 2015 10:47:32 GMT"
// },
// size: 913,
// aborted: false,
// rt: 1911,
// keepAliveSocket: false
// },
// data: [{
// Name: "200-200",
// Content: "0e_200w_200h_0c_0i_0o_90Q_1x.jpg",
// CreateTime: "Thu, 19 Mar 2015 08:28:08 GMT",
// LastModifyTime: "Thu, 19 Mar 2015 08:28:08 GMT"
// }, {
// Name: "800",
// Content: "800w_90Q_1x.jpg",
// CreateTime: "Thu, 19 Mar 2015 08:29:15 GMT",
// LastModifyTime: "Thu, 19 Mar 2015 08:29:15 GMT"
// }, {
// Name: "400",
// Content: "400w_90Q_1x.jpg",
// CreateTime: "Thu, 19 Mar 2015 08:34:21 GMT",
// LastModifyTime: "Thu, 19 Mar 2015 08:34:21 GMT"
// }, {
// Name: "600",
// Content: "600w_90Q_1x.jpg",
// CreateTime: "Thu, 19 Mar 2015 08:35:02 GMT",
// LastModifyTime: "Thu, 19 Mar 2015 08:35:02 GMT"
// }]
// }
// TODO
Create a signature url for directly download.
parameters:
1800Success will return full signature url.
example:
var url = imgClient.signatureUrl('
');
// http://thumbnail.myimageservice.com/demo.jpg@200w_200h?OSSAccessKeyId=uZxyLARzYZtGwHKY&Expires=1427803849&Signature=JSPRe06%2FjQpQSj5zlx2ld1V%2B35I%3D
Cluster mode now only support object operations.
var Cluster = require('ali-oss').ClusterClient;
var client = Cluster({
cluster: [{
host: 'host1',
accessKeyId: 'id1',
accessKeySecret: 'secret1'
}, {
host: 'host2',
accessKeyId: 'id2',
accessKeySecret: 'secret2'
}],
schedule: 'masterSlave', //default is `roundRobin`
});
// listen error event to logging error
client.on('error', function(err) {
console.error(err.stack);
});
// client init ready
client.ready(function() {
console.log('cluster client init ready, go ahead!');
});
Will choose an alive client by schedule(masterSlave or roundRobin).
client.get()client.head()client.getStream()client.list()client.signatureUrl()client.chooseAvailable() - choose an available client by schedule.Will put to all clients.
client.put()client.putStream()client.delete()client.deleteMulti()client.copy()client.putMeta()We provide an async wrapper which can be used without co. All the
methods are preserved, just in a async way:
var OSS = require('ali-oss').Wrapper;
var STS = OSS.STS;
var client = new OSS({ /* same options */});
client.put('hello', new Buffer('world')).then(function (val) {
console.log('result: %j', val);
}).catch (function (err) {
console.log('error: %j', err);
});
client.get('hello').then(function (val) {
console.log('result: %j', val);
}).catch (function (err) {
console.log('error: %j', err);
});
var url = client.signatureUrl('hello');
console.log(url);
var stsClient = new STS({ /* same options */});
var role = 'role';
stsClient.assumeRole(role).then(function (val) {
console.log('result: %j', val);
}).catch (function (err) {
console.log('error: %j', err);
});
You can use most of the functionalities of ali-oss in browser with
some exceptions:
As browser-side javascript involves CORS operations. You need to setup your bucket CORS rules to allow CORS operations:
As we don't want to expose the accessKeyId/accessKeySecret in the browser, a common practice is to use STS to grant temporary access.
Include the sdk lib in the <script> tag and you have OSS available
for creating client. We use OSS.Wrapper here to avoid using co:
<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk.min.js"></script>
<script type="text/javascript">
var client = new OSS.Wrapper({
region: 'oss-cn-hangzhou',
accessKeyId: '<access-key-id>',
accessKeySecret: '<access-key-secret>',
bucket: '<bucket-name>'
});
client.list().then(function (result) {
console.log('objects: %j', result.objects);
return client.put('my-obj', new OSS.Buffer('hello world'));
}).then(function (result) {
console.log('put result: %j', result);
return client.get('my-obj');
}).then(function (result) {
console.log('get result: %j', result.content.toString());
});
</script>
The full sample can be found here.
npm run build-dist
And see the build artifacts under dist/.
Each error return by OSS server will contains these properties:
| name | status | message | message in Chinese |
|---|---|---|---|
| AccessDeniedError | 403 | Access Denied | 拒绝访问 |
| BucketAlreadyExistsError | 409 | Bucket already exists | Bucket 已经存在 |
| BucketNotEmptyError | 409 | Bucket is not empty | Bucket 不为空 |
| EntityTooLargeError | 400 | Entity too large | 实体过大 |
| EntityTooSmallError | 400 | Entity too small | 实体过小 |
| FileGroupTooLargeError | 400 | File group too large | 文件组过大 |
| InvalidLinkNameError | 400 | Link name can't be the same as the object name | Object Link 与指向的 Object 同名 |
| LinkPartNotExistError | 400 | Can't link to not exists object | Object Link 中指向的 Object 不存在 |
| ObjectLinkTooLargeError | 400 | Too many links to this object | Object Link 中 Object 个数过多 |
| FieldItemTooLongError | 400 | Post form fields items too large | Post 请求中表单域过大 |
| FilePartInterityError | 400 | File part has changed | 文件 Part 已改变 |
| FilePartNotExistError | 400 | File part not exists | 文件 Part 不存在 |
| FilePartStaleError | 400 | File part stale | 文件 Part 过时 |
| IncorrectNumberOfFilesInPOSTRequestError | 400 | Post request contains invalid number of files | Post 请求中文件个数非法 |
| InvalidArgumentError | 400 | Invalid format argument | 参数格式错误 |
| InvalidAccessKeyIdError | 400 | Access key id not exists | Access Key ID 不存在 |
| InvalidBucketNameError | 400 | Invalid bucket name | 无效的 Bucket 名字 |
| InvalidDigestError | 400 | Invalid digest | 无效的摘要 |
| InvalidEncryptionAlgorithmError | 400 | Invalid encryption algorithm | 指定的熵编码加密算法错误 |
| InvalidObjectNameError | 400 | Invalid object name | 无效的 Object 名字 |
| InvalidPartError | 400 | Invalid part | 无效的 Part |
| InvalidPartOrderError | 400 | Invalid part order | 无效的 part 顺序 |
| InvalidPolicyDocumentError | 400 | Invalid policy document | 无效的 Policy 文档 |
| InvalidTargetBucketForLoggingError | 400 | Invalid bucket on logging operation | Logging 操作中有无效的目标 bucket |
| InternalError | 500 | OSS server internal error | OSS 内部发生错误 |
| MalformedXMLError | 400 | Malformed XML format | XML 格式非法 |
| MalformedPOSTRequestError | 400 | Invalid post body format | Post 请求的 body 格式非法 |
| MaxPOSTPreDataLengthExceededError | 400 | Post extra data too large | Post 请求上传文件内容之外的 body 过大 |
| MethodNotAllowedError | 405 | Not allowed method | 不支持的方法 |
| MissingArgumentError | 411 | Missing argument | 缺少参数 |
| MissingContentLengthError | 411 | Missing Content-Length header |
缺少内容长度 |
| NoSuchBucketError | 404 | Bucket not exists | Bucket 不存在 |
| NoSuchKeyError | 404 | Object not exists | 文件不存在 |
| NoSuchUploadError | 404 | Multipart upload id not exists | Multipart Upload ID 不存在 |
| NotImplementedError | 501 | Not implemented | 无法处理的方法 |
| PreconditionFailedError | 412 | Pre condition failed | 预处理错误 |
| RequestTimeTooSkewedError | 403 | Request time exceeds 15 minutes to server time | 发起请求的时间和服务器时间超出 15 分钟 |
| RequestTimeoutError | 400 | Request timeout | 请求超时 |
| RequestIsNotMultiPartContentError | 400 | Invalid post content-type | Post 请求 content-type 非法 |
| SignatureDoesNotMatchError | 403 | Invalid signature | 签名错误 |
| TooManyBucketsError | 400 | Too many buckets on this user | 用户的 Bucket 数目超过限制 |