You can use most of the functionalities of ali-oss in browser with some exceptions:
put object with streaming: no chunked encoding, we use multipart upload instead
get object to local file: we cannot manipulate file system in browser, we provide signed object url for downloading needs
bucket operations(listBuckets, putBucketLogging, etc) will fail: OSS server currently do not support CORS requests for bucket operations (will probably be fixed later)
Compatibility
IE >= 10 & Edge
Major versions of Chrome/Firefox/Safari
Major versions of Android/iOS/WP
Note: Because some browsers do not support promises, you need to introduce promise compatible libraries.
For example: IE10 and IE11 need to introduce a promise-polyfill.
Setup
Bucket setup
As browser-side javascript involves CORS operations. You need to setup your bucket CORS rules to allow CORS operations:
set allowed origins to ‘*‘
allowed methods to ‘PUT, GET, POST, DELETE, HEAD’
set allowed headers to ‘*‘
expose ‘ETag’ in expose headers
STS setup
As we don’t want to expose the accessKeyId/accessKeySecret in the browser, a common practice is to use STS to grant temporary access.
Basic usage
Include the sdk lib in the <script> tag and you have OSS available for creating client.
// x.x.x The specific version number represented // we recommend introducing offline resources, because the usability of
online resources depends on the stability of the cdn server.
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.
Create A Bucket Instance
Each OSS instance required accessKeyId, accessKeySecret and bucket.
oss(options)
Create a Bucket store instance.
options:
accessKeyId {String} access key you create on aliyun console website
accessKeySecret {String} access secret you create
[stsToken] {String} used by temporary authorization, detail see
[refreshSTSToken] {Function} used by auto set stsToken、accessKeyId、accessKeySecret when sts info expires. return value must be object contains stsToken、accessKeyId、accessKeySecret
[refreshSTSTokenInterval] {number} use time (ms) of refresh STSToken interval it should be less than sts info expire interval, default is 300000ms(5min)
[bucket] {String} the default bucket you want to access If you don’t have any bucket, please use putBucket() create one first.
[endpoint] {String} oss region domain. It takes priority over region. Set as extranet domain name, intranet domain name, accelerated domain name, etc. according to different needs. please see endpoints
[region] {String} the bucket data region location, please see Data Regions, default is oss-cn-hangzhou.
[internal] {Boolean} access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save a lot of money.
[secure] {Boolean} instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol.
[timeout] {String|Number} instance level timeout for all operations, default is 60s.
[cname] {Boolean}, default false, access oss with custom domain name. if true, you can fill endpoint field with your custom domain name,
[isRequestPay] {Boolean}, default false, whether request payer function of the bucket is open, if true, will send headers 'x-oss-request-payer': 'requester' to oss server. the details you can see requestPay
[useFetch] {Boolean}, default false, it just work in Browser, if true,it means upload object with fetch mode ,else XMLHttpRequest
[enableProxy] {Boolean}, Enable proxy request, default is false. NOTE: When enabling proxy request, please ensure that proxy-agent is installed.
[proxy] {String | Object}, proxy agent uri or options, default is null.
[retryMax] {Number}, used by auto retry send request count when request error is net error or timeout. NOTE: Not support put with stream, putStream, append with stream because the stream can only be consumed once
[maxSockets] {Number} Maximum number of sockets to allow per host. Default is infinity
[authorizationV4] {Boolean} Use V4 signature. Default is false.
[cloudBoxId] {String} the CloudBox ID you want to access. When configuring this option, please set the endpoint option to the CloudBox endpoint and set the authorizationV4 option to true.
example:
basic usage
const OSS = require('ali-oss');
const store =new OSS({
accessKeyId:'your access key',
accessKeySecret:'your access secret',
bucket:'your bucket name',
region:'oss-cn-hangzhou'
});
use accelerate endpoint
Global accelerate endpoint: oss-accelerate.aliyuncs.com
Accelerate endpoint of regions outside mainland China: oss-accelerate-overseas.aliyuncs.com
const OSS = require('ali-oss');
const store =new OSS({
accessKeyId:'your access key',
accessKeySecret:'your access secret',
bucket:'your bucket name',
endpoint:'oss-accelerate.aliyuncs.com'
});
use custom domain
const OSS = require('ali-oss');
const store =new OSS({
accessKeyId:'your access key',
accessKeySecret:'your access secret',
cname:true,
endpoint:'your custome domain'
});
use STS and refreshSTSToken
const OSS = require('ali-oss');
const store =new OSS({
accessKeyId:'your STS key',
accessKeySecret:'your STS secret',
stsToken:'your STS token',
refreshSTSToken: async ()=>{
const info = await fetch('you sts server');
return{
accessKeyId: info.accessKeyId,
accessKeySecret: info.accessKeySecret,
stsToken: info.stsToken
};
},
refreshSTSTokenInterval:300000
});
retry request with stream
for(let i =0; i <= store.options.retryMax; i++){
try{
const result = await store.putStream('<example-object>', fs.createReadStream('<example-path>'));
console.log(result);
break;// break if success
}catch(e){
console.log(e);
}
}
use V4 signature, and use optional additionalHeaders option which type is a string array, and the values inside need to be included in the header.
// The keys of the request headers that need to be calculated into the V4 signature. Please ensure that these additional headers are included in the request headers.
owner {Object} object owner, including id and displayName
isTruncated {Boolean} truncate or not
nextMarker {String} next marker string
res {Object} response info, including
status {Number} response status
headers {Object} response headers
size {Number} response size
rt {Number} request total use time (ms)
example:
List top 10 buckets
store
.listBuckets({
'max-keys':10
})
.then(result =>{
console.log(result);
});
.putBucket(name[, options])
Create a new bucket.
parameters:
name {String} bucket name If bucket exists and not belong to current account, will throw BucketAlreadyExistsError. If bucket not exists, will create a new bucket and set it’s ACL.
[options] {Object} optional parameters
[acl] {String} include private,public-read,public-read-write
[storageClass] {String} the storage type include (Standard,IA,Archive)
[dataRedundancyType] {String} default LRS, include LRS,ZRS
[timeout] {Number} the operation timeout
Success will return the bucket name on bucket properties.
bucket {String} bucket name
res {Object} response info, including
status {Number} response status
headers {Object} response headers
size {Number} response size
rt {Number} request total use time (ms)
example:
Create a bucket name helloworld location on HongKong
store.putBucket('helloworld').then(result =>{
// use it by default
store.useBucket('helloworld');
});
Create a bucket name helloworld location on HongKong StorageClass Archive
Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、 Owner、AccessControlList、Versioning
parameters:
name {String} bucket name
example:
Use helloworld as the default bucket
store.getBucketInfo('helloworld').then(res =>{
console.log(res.bucket);
});
.getBucketStat(name)
Call the GetBucketStat interface to get the storage capacity of the specified storage space (Bucket) and the number of files (Object).
Calling this interface requires the oss:GetBucketStat permission. The data obtained by calling this interface is not real-time data and may be delayed for more than an hour. The point in time of the stored information obtained by calling this interface is not guaranteed to be up-to-date, i.e. the LastModifiedTime field returned by a later call to this interface may be smaller than the LastModifiedTime field returned by a previous call to this interface.
parameters:
name {String} bucket name
Success will return:
stat {Object} container for the BucketStat structure:
Storage {String} the total storage capacity of the Bucket, in bytes.
ObjectCount {String} total number of Objects in the Bucket。
MultipartUploadCount {String} the number of Multipart Uploads in the Bucket that have been initialized but not yet completed (Complete) or not yet aborted (Abort).
LiveChannelCount {String} the number of Live Channels in the Bucket.
LastModifiedTime {String} the point in time, in timestamps, when the storage information was retrieved.
StandardStorage {String} the amount of storage of the standard storage type, in bytes.
StandardObjectCount {String} the number of objects of the standard storage type.
InfrequentAccessStorage {String} the amount of billed storage for the low-frequency storage type, in bytes.
InfrequentAccessRealStorage {String} the actual storage amount of the low-frequency storage type, in bytes.
InfrequentAccessObjectCount {String} the number of Objects of the low-frequency storage type.
ArchiveStorage {String} the amount of billed storage for the archive storage type, in bytes.
ArchiveRealStorage {String} the actual storage amount of the archive storage type, in bytes.
ArchiveObjectCount {String} the number of objects of the archive storage type.
ColdArchiveStorage {String} the amount of billed storage for the cold archive storage type, in bytes.
ColdArchiveRealStorage {String} the actual storage amount in bytes for the cold archive storage type.
ColdArchiveObjectCount {String} the number of objects of the cold archive storage type.
res {Object} response info, including
status {Number} response status
headers {Object} response headers
size {Number} response size
rt {Number} request total use time (ms)
example:
If you don’t fill in the name, the default is the bucket defined during initialization.
[expiredObjectDeleteMarker] {String} value true createdBeforeDate and days and expiredObjectDeleteMarker must have one.
[abortMultipartUpload] {Object} Specifies the expiration attribute of the multipart upload tasks that are not complete.
[days] {Number|String} expire after the days
[createdBeforeDate] {String} expire date, e.g.: 2022-10-11T00:00:00.000Z createdBeforeDate and days must have one.
[transition] {Object} Specifies the time when an object is converted to the IA or archive storage class during a valid life cycle.
storageClass {String} Specifies the storage class that objects that conform to the rule are converted into. allow values: IA or Archive or ColdArchive or DeepColdArchive
[days] {Number|String} expire after the days
[createdBeforeDate] {String} expire date, e.g.: 2022-10-11T00:00:00.000Z createdBeforeDate and days must have one.
[noncurrentVersionTransition] {Object} Specifies the time when an object is converted to the IA or archive storage class during a valid life cycle.
storageClass {String} Specifies the storage class that history objects that conform to the rule are converted into. allow values: IA or Archive or ColdArchive or DeepColdArchive
noncurrentDays {String} expire after the noncurrentDays expiration、 abortMultipartUpload、 transition、 noncurrentVersionTransition must have one.
[noncurrentVersionExpiration] {Object} specifies the expiration attribute of the lifecycle rules for the history object.
noncurrentDays {String} expire after the noncurrentDays
[tag] {Object} Specifies the object tag applicable to a rule. Multiple tags are supported.
key {String} Indicates the tag key.
value {String} Indicates the tag value. tag cannot be used with abortMultipartUpload
[options] {Object} optional parameters
[timeout] {Number} the operation timeout
Success will return:
res {Object} response info, including
status {Number} response status
headers {Object} response headers
size {Number} response size
rt {Number} request total use time (ms)
example:
store
.putBucketLifecycle('hello',[
{
id:'delete after one day',
prefix:'logs/',
status:'Enabled',
days:1
},
{
prefix:'logs2/',
status:'Disabled',
date:'2022-10-11T00:00:00.000Z'
}
])
.then(result =>{});
example: for history with noncurrentVersionExpiration
const result = await store.putBucketLifecycle(bucket,[
{
id:'expiration1',
prefix:'logs/',
status:'Enabled',
expiration:{
days:'1'
},
noncurrentVersionExpiration:{
noncurrentDays:'1'
}
}
]);
console.log(result);
example: for history with expiredObjectDeleteMarker
const result = await store.putBucketLifecycle(bucket,[
{
id:'expiration1',
prefix:'logs/',
status:'Enabled',
expiration:{
expiredObjectDeleteMarker:'true'
},
noncurrentVersionExpiration:{
noncurrentDays:'1'
}
}
]);
console.log(result);
example: for history with noncurrentVersionTransition
const result = await store.putBucketLifecycle(bucket,[
{
id:'expiration1',
prefix:'logs/',
status:'Enabled',
noncurrentVersionTransition:{
noncurrentDays:'10',
storageClass:'IA'
}
}
]);
console.log(result);
.getBucketLifecycle(name[, options])
Get the bucket object lifecycle.
parameters:
name {String} bucket name
[options] {Object} optional parameters
[timeout] {Number} the operation timeout
Success will return:
rules {Array} the lifecycle rule list
res {Object} response info, including
status {Number} response status
headers {Object} response headers
size {Number} response size
rt {Number} request total use time (ms)
.deleteBucketLifecycle(name[, options])
Delete the bucket object lifecycle.
parameters:
name {String} bucket name
[options] {Object} optional parameters
[timeout] {Number} the operation timeout
Success will return:
res {Object} response info, including
status {Number} response status
headers {Object} response headers
size {Number} response size
rt {Number} request total use time (ms)
.putBucketCORS(name, rules[, options])
Set CORS rules of the bucket object
parameters:
name {String} bucket name
rules {Array} rule config list, each Rule will contains below properties:
allowedOrigin {String/Array} configure for Access-Control-Allow-Origin header
allowedMethod {String/Array} configure for Access-Control-Allow-Methods header
[allowedHeader] {String/Array} configure for Access-Control-Allow-Headers header
[exposeHeader] {String/Array} configure for Access-Control-Expose-Headers header
[maxAgeSeconds] {String} configure for Access-Control-Max-Age header
used to extend the retention period of objects in a bucket whose retention policy is locked.
parameters:
name {String} the bucket name
wormId {String} worm id
days {String | Number} retention days
[options] {Object} optional args
Success will return:
status {Number} response status
res {Object} response info
.getBucketWorm(name[, options])
used to query the retention policy information of the specified bucket.
parameters:
name {String} the bucket name
[options] {Object} optional args
Success will return:
wormId {String} worm id
state {String} Locked or InProgress
days {String} retention days
creationDate {String}
status {Number} response status
res {Object} response info
.initiateBucketWorm(name, days[, options])
create a retention policy.
parameters:
name {String} the bucket name
days {String | Number}} set retention days
[options] {Object} optional args
Success will return:
wormId {String} worm id
status {Number} response status
res {Object} response info
Object Operations
All operations function return Promise, except signatureUrl.
.put(name, file[, options])
Add an object to the bucket.
parameters:
name {String} object name store on OSS
file {String|Buffer|ReadStream|File(only support Browser)|Blob(only support Browser)} object local path, content buffer or ReadStream content instance use in Node, Blob and html5 File
[options] {Object} optional parameters
[timeout] {Number} the operation timeout (ms)
[mime] {String} custom mime, will send with Content-Type entity header
[meta] {Object} user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 }
[callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail see
url {String} After a file is uploaded successfully, the OSS sends a callback request to this URL.
[host] {String} The host header value for initiating callback requests.
body {String} The value of the request body when a callback is initiated, for example, key=${key}&etag=${etag}&my_var=${x:my_var}.
[contentType] {String} The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value.
[callbackSNI] {Boolean} Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
[customValue] {Object} Custom parameters are a map of key-values
e.g.:
var customValue ={ var1:'value1', var2:'value2'};
[headers] {Object} extra headers
‘Cache-Control’ cache control for download, e.g.: Cache-Control: public, no-cache
‘Content-Disposition’ object name for download, e.g.: Content-Disposition: somename
‘Content-Encoding’ object content encoding for download, e.g.: Content-Encoding: gzip
‘Expires’ expires time for download, an absolute date and time. e.g.: Tue, 08 Dec 2020 13:49:43 GMT
[disabledMD5] {Boolean} default true, it just work in Browser. if false,it means that MD5 is automatically calculated for uploaded files. NOTE: Synchronous computing tasks will block the main process
Success will return the object information.
object:
name {String} object name
data {Object} callback server response data, sdk use JSON.parse() return
[contentLength] {Number} the stream length, chunked encoding will be used if absent
[timeout] {Number} the operation timeout
[mime] {String} custom mime, will send with Content-Type entity header
[meta] {Object} user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 }
[callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail see
url {String} After a file is uploaded successfully, the OSS sends a callback request to this URL.
[host] {String} The host header value for initiating callback requests.
body {String} The value of the request body when a callback is initiated, for example, key=${key}&etag=${etag}&my_var=${x:my_var}.
[contentType] {String} The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value.
[callbackSNI] {Boolean} Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
[customValue] {Object} Custom parameters are a map of key-values
e.g.:
var customValue ={ var1:'value1', var2:'value2'};
[headers] {Object} extra headers, detail see RFC 2616
‘Cache-Control’ cache control for download, e.g.: Cache-Control: public, no-cache
‘Content-Disposition’ object name for download, e.g.: Content-Disposition: somename
‘Content-Encoding’ object content encoding for download, e.g.: Content-Encoding: gzip
‘Expires’ expires time for download, an absolute date and time. e.g.: Tue, 08 Dec 2020 13:49:43 GMT
// cdnUrl should be `https://mycdn.domian.com/foo/bar.jpg`
.generateObjectUrl(name[, baseUrl])
Get the Object url. If provide baseUrl, will use baseUrl instead the default bucket and endpoint. Suggest use generateObjectUrl instead of getObjectUrl.
[file] {String|WriteStream|Object} file path or WriteStream instance to store the content If file is null or ignore this parameter, function will return info contains content property. If file is Object, it will be treated as options.
[options] {Object} optional parameters
[versionId] {String} the version id of history object
[timeout] {Number} the operation timeout
[process] {String} image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'}
[responseCacheControl] {String} default no-cache, (only support Browser). response-cache-control, will response with HTTP Header Cache-Control
[headers] {Object} extra headers, detail see RFC 2616
‘Range’ get specifying range bytes content, e.g.: Range: bytes=0-9
‘If-Modified-Since’ object modified after this time will return 200 and object meta, otherwise return 304 not modified
‘If-Unmodified-Since’ object modified before this time will return 200 and object meta, otherwise throw PreconditionFailedError
‘If-Match’ object etag equal this will return 200 and object meta, otherwise throw PreconditionFailedError
‘If-None-Match’ object etag not equal this will return 200 and object meta, otherwise return 304 not modified
Success will return the info contains response.
object:
[content] {Buffer} file content buffer if file parameter is null or ignore
res {Object} response info, including
status {Number} response status
headers {Object} response headers
size {Number} response size
rt {Number} request total use time (ms)
If object not exists, will throw NoSuchKeyError.
example:
Get an exists object and store it to the local file
const filepath ='/home/ossdemo/demo.txt';
await store.get('ossdemo/demo.txt', filepath);
_ Store object to a writestream
await store.get('ossdemo/demo.txt', somestream);
Get an object content buffer
const result = await store.get('ossdemo/demo.txt');
console.log(Buffer.isBuffer(result.content));
Get a processed image and store it to the local file
[sourceBucket] {String} source Bucket. if doesn’t exist,sourceBucket is same bucket.
[options] {Object} optional parameters
[versionId] {String} the version id of history object
[timeout] {Number} the operation timeout
[meta] {Object} user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } If the meta set, will override the source object meta.
[headers] {Object} extra headers
‘If-Match’ do copy if source object etag equal this, otherwise throw PreconditionFailedError
‘If-None-Match’ do copy if source object etag not equal this, otherwise throw PreconditionFailedError
‘If-Modified-Since’ do copy if source object modified after this time, otherwise throw PreconditionFailedError
‘If-Unmodified-Since’ do copy if source object modified before this time, otherwise throw PreconditionFailedError