aliyun OSS(Object Storage Service) js client for Node and Browser env.
`NOTE`: For SDK `5.X` document, please go to [README.md](https://github.com/ali-sdk/ali-oss/blob/5.x/README.md)
## Install
```bash
npm install ali-oss --save
```
## Compatibility
### Node
Node.js >= 8.0.0 required. You can use 4.x in Node.js <8.
### Browser
- IE >= 10 & Edge
- Major versions of Chrome/Firefox/Safari
- Major versions of Android/iOS/WP
`Note`:
- For Lower browsers you can refer to [PostObject](https://help.aliyun.com/document_detail/31988.html), if you want to see more practices ,please refer to [Web Post](https://help.aliyun.com/document_detail/31923.html)
### QA
You can join DingDing Talk Group, [Group Link](https://qr.dingtalk.com/action/joingroup?code=v1,k1,E60EuCmxajfilkaR/kknRcGR9UissskPEXu/1td36z0=)
Go to [OSS website](http://www.aliyun.com/product/oss/?lang=en), 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](https://www.alibabacloud.com/help/doc-detail/32077.htm)
- [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](https://www.alibabacloud.com/help/doc-detail/31837.htm)
- [region] {String} the bucket data region location, please see [Data Regions](#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 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](https://help.aliyun.com/document_detail/91337.htm)
- [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.
- [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
example:
1. basic usage
```js
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'
});
```
2. use accelerate endpoint
- Global accelerate endpoint: oss-accelerate.aliyuncs.com
- Accelerate endpoint of regions outside mainland China: oss-accelerate-overseas.aliyuncs.com
```js
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'
});
```
3. use custom domain
```js
const OSS = require('ali-oss');
const store = new OSS({
accessKeyId: 'your access key',
accessKeySecret: 'your access secret',
cname: true,
endpoint: 'your custome domain'
});
```
4. use STS and refreshSTSToken
```js
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
});
```
5. retry request with stream
```js
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);
}
}
```
## Bucket Operations
### .listBuckets(query[, options])
List buckets in this account.
parameters:
- [query] {Object} query parameters, default is `null`
- [prefix] {String} search buckets using `prefix` key
- [marker] {String} search start from `marker`, including `marker` key
- [max-keys] {String|Number} max buckets, default is `100`, limit to `1000`
- [options] {Object} optional parameters
- [timeout] {Number} the operation timeout
Success will return buckets list on `buckets` properties.
- buckets {Array<BucketMeta>} bucket meta info list
Each `BucketMeta` will contains blow properties:
- name {String} bucket name
- region {String} bucket store data region, e.g.: `oss-cn-hangzhou-a`
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
```js
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.
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](https://www.alibabacloud.com/help/doc-detail/31989.htm)<br>
- 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.
- [customValue] {Object} Custom parameters are a map of key-values<br>
e.g.:
```js
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`
- See more: [PutObject](https://help.aliyun.com/document_detail/31978.html#title-yxe-96d-x61)
- [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](https://www.alibabacloud.com/help/doc-detail/31989.htm)<br>
- 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.
- [customValue] {Object} Custom parameters are a map of key-values<br>
e.g.:
```js
var customValue = { var1: 'value1', var2: 'value2' };
```
- [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
- '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`
- storageClass {String} storage class type, e.g.: `Standard`
- owner {Object|null} object owner, including `id` and `displayName`
- prefixes {Array<String>} prefix list
- isTruncated {Boolean} truncate or not
- nextContinuationToken {String} next continuation-token string
- keyCount {Number} The number of keys returned for this request. If Delimiter is specified, KeyCount is the sum of the elements in Key and CommonPrefixes.
- res {Object} response info, including
- status {Number} response status
- headers {Object} response headers
- size {Number} response size
- rt {Number} request total use time (ms)
- List top 10 objects
```js
const result = await store.listV2({
'max-keys': 10
});
console.log(result.objects);
```
- List `fun/` dir including subdirs objects
```js
const result = await store.listV2({
prefix: 'fun/'
});
console.log(result.objects);
```
- List `fun/` dir objects, not including subdirs
```js
const result = await store.listV2({
prefix: 'fun/',
delimiter: '/'
});
console.log(result.objects);
```
- List `a/` dir objects, after `a/b` and not include `a/b`
```js
const result = await store.listV2({
delimiter: '/',
prefix: 'a/',
'start-after': 'a/b'
});
console.log(result.objects);
```
### .getBucketVersions(query[, options])
List the version information of all objects in the bucket, including the delete marker (Delete Marker).
parameters:
- [query] {Object} query parameters, default is `null`
- [prefix] {String} search object using `prefix` key
- [versionIdMarker] {String} set the result to return from the version ID marker of the key marker object and sort by the versions
- [keyMarker] {String} search start from `keyMarker`, including `keyMarker` key
- [encodingType] {String} specifies that the returned content is encoded, and specifies the type of encoding
- [delimiter] {String} delimiter search scope
e.g. `/` only search current dir, not including subdir
- [maxKeys] {String|Number} max objects, default is `100`, limit to `1000`
- [options] {Object} optional parameters
- [timeout] {Number} the operation timeout
Success will return objects list on `objects` properties.
- objects {Array<ObjectMeta>} object meta info list
Each `ObjectMeta` will contains blow properties:
- name {String} object name on oss
- lastModified {String} object last modified GMT date, e.g.: `2015-02-19T08:39:44.000Z`
- storageClass {String} storage class type, e.g.: `Standard`
- owner {Object} object owner, including `id` and `displayName`
- deleteMarker {Array<ObjectDeleteMarker>} object delete marker info list
Each `ObjectDeleteMarker`
- name {String} object name on oss
- lastModified {String} object last modified GMT date, e.g.: `2015-02-19T08:39:44.000Z`
- versionId {String} object versionId
- isTruncated {Boolean} truncate or not
- nextKeyMarker (nextMarker) {String} next marker string
- nextVersionIdMarker (NextVersionIdMarker) {String} next version ID 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:
- View all versions of objects and deleteMarker of bucket
```js
const result = await store.getBucketVersions();
console.log(result.objects);
console.log(result.deleteMarker);
```
- List from key-marker
```js
const result = await store.getBucketVersions({
keyMarker: 'keyMarker'
});
console.log(result.objects);
```
- List from the version-id-marker of key-marker
```js
const result = await store.getBucketVersions({
versionIdMarker: 'versionIdMarker',
keyMarker: 'keyMarker'
});
console.log(result.objects);
console.log(result.deleteMarker);
```
### .signatureUrl(name[, options])
Create a signature url for download or upload object. When you put object with signatureUrl ,you need to pass `Content-Type`.Please look at the example.
parameters:
- name {String} object name store on OSS
- [options] {Object} optional parameters
- [expires] {Number} after expires seconds, the url will become invalid, default is `1800`
- [method] {String} the HTTP method, default is 'GET'
- [Content-Type] {String} set the request content type
- [process] {String} image process params, will send with `x-oss-process`
- [versionId] {String} the version id of history object
Success will return
- targetName {String} target object 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:
```js
const result = await store.getSymlink('ossdemo.txt');
console.log(result.targetName);
```
for history object
```js
const versionId = 'object versionId';
const result = await store.getSymlink('ossdemo.txt', { versionId });
console.log(result.targetName);
```
### .initMultipartUpload(name[, options])
Before transmitting data in the Multipart Upload mode,
you must call the Initiate Multipart Upload interface to notify the OSS to initiate a Multipart Upload event.
The Initiate Multipart Upload interface returns a globally unique Upload ID created by the OSS server to identify this Multipart Upload event.
parameters:
- name {String} object name
- [options] {Object} optional parameters
- [timeout] {Number} the operation timeout
- [mime] Mime file type e.g.: application/octet-stream
- [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
- [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`
- [x-oss-server-side-encryption]
Specify the server-side encryption algorithm used to upload each part of this object,Type: string, Valid value: AES256 `x-oss-server-side-encryption: AES256`<br>
if use in browser you should be set cors expose header x-oss-server-side-encryption
- See more: [InitiateMultipartUpload](https://help.aliyun.com/document_detail/31992.html?#title-wh0-a2h-rur)
Success will return:
- res {Object} response info, including
- status {Number} response status
- headers {Object} response headers
- [x-oss-server-side-encryption] if set request header x-oss-server-side-encryption, will return
- size {Number} response size
- rt {Number} request total use time (ms)
- bucket {String} bucket name
- name {String} object name store on OSS
- uploadId {String} upload id, use for uploadPart, completeMultipart
example:
```js
const result = await store.initMultipartUpload('object');
Using Upload Part Copy, you can copy data from an existing object and upload a part of the data.
When copying a file larger than 1 GB, you must use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object.
parameters:
- name {String} object name
- uploadId {String} get by initMultipartUpload api
- partNo {Number} range is 1-10000, If this range is exceeded, OSS returns the InvalidArgument's error code.
- range {String} Multipart Upload requires that the size of any Part other than the last Part is greater than 100KB, range value like `0-102400`
- sourceData {Object}
- sourceKey {String} the source object name
- sourceBucketName {String} the source bucket name
- [options] {Object} optional parameters
- [timeout] {Number} the operation timeout
- [versionId] {String} the version id of history object
- [headers] {Object} The following request header is used for the source objects specified by x-oss-copy-source.
- [x-oss-copy-source-if-match] default none<br>
If the ETAG value of the source object is equal to the ETAG value provided by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
If the source object has not been modified since the time specified by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
If the time specified by the received parameter is the same as or later than the modification time of the file, the system transfers the file normally, and returns 200 OK; otherwise, the system returns 412 Precondition Failed.
If the source object has been modified since the time specified by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
- [callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail [see](https://www.alibabacloud.com/help/doc-detail/31989.htm)<br>
- 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.
- [customValue] {Object} Custom parameters are a map of key-values<br>
e.g.:
```js
var customValue = { var1: 'value1', var2: 'value2' };
```
- [headers] {Object} extra headers, detail see [CompleteMultipartUpload](https://help.aliyun.com/document_detail/31995.html?#title-nan-5y3-rjd)
Upload file with [OSS multipart][oss-multipart].<br>
this function contains initMultipartUpload, uploadPart, completeMultipartUpload.
When you use multipartUpload api,if you encounter problems with ConnectionTimeoutError, you should handle ConnectionTimeoutError in your business code. How to resolve ConnectionTimeoutError, you can decrease `partSize` size 、 Increase `timeout` 、Retry request ,
or give tips in your business code;
parameters:
- name {String} object name
- file {String|File(only support Browser)|Blob(only support Browser)|Buffer} file path or HTML5 Web File or web Blob or content buffer
- [options] {Object} optional args
- [parallel] {Number} the number of parts to be uploaded in parallel
- [partSize] {Number} the suggested size for each part, defalut `1024 * 1024`(1MB), minimum `100 * 1024`(100KB)
- [progress] {Function} function | async | Promise, the progress callback called after each
successful upload of one part, it will be given three parameters:
(percentage {Number}, checkpoint {Object}, res {Object})
- [checkpoint] {Object} the checkpoint to resume upload, if this is
provided, it will continue the upload from where interrupted,
otherwise a new multipart upload will be created.
- file {File} The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings
- name {String} object key
- fileSize {Number} file size
- partSize {Number} part size
- uploadId {String} upload id
- doneParts {Array} An array of pieces that have been completed, including the object structure as follows
- number {Number} part number
- etag {String} part etag
- [meta] {Object} user meta, will send with `x-oss-meta-` prefix string
- [mime] {String} custom mime , will send with `Content-Type` entity header
- [callback] {Object} The callback parameter is composed of a JSON string encoded in Base64,detail [see](https://www.alibabacloud.com/help/doc-detail/31989.htm)<br>
- 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.
- [customValue] {Object} Custom parameters are a map of key-values<br>
e.g.:
```js
var customValue = { var1: 'value1', var2: 'value2' };
```
- [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
- '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`
- **NOTE**: Some headers are [disabled in browser][disabled-browser-headers]
- [timeout] {Number} Milliseconds before a request is considered to be timed out
- [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
Copy file with [OSS multipart][oss-multipart]. <br>
this function contains head, initMultipartUpload, uploadPartCopy, completeMultipartUpload.<br>
When copying a file larger than 1 GB, you should use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object.
parameters:
- name {String} object name
- file {String|File} file path or HTML5 Web File
- [options] {Object} optional args
- [timeout] {Number} Milliseconds before a request is considered to be timed out
- [parallel] {Number} the number of parts to be uploaded in parallel
- [partSize] {Number} the suggested size for each part, defalut `1024 * 1024`(1MB), minimum `100 * 1024`(100KB)
- [versionId] {String} the version id of history object
- [progress] {Function} function | async | Promise, the progress callback called after each
successful upload of one part, it will be given three parameters:
(percentage {Number}, checkpoint {Object}, res {Object})
- [checkpoint] {Object} the checkpoint to resume upload, if this is
provided, it will continue the upload from where interrupted,
otherwise a new multipart upload will be created.
- [headers] {Object} extra headers, detail see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616.html)
- '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`
- **NOTE**: Some headers are [disabled in browser][disabled-browser-headers]
- [copyheaders] {Object} only uploadPartCopy api used, detail [see](https://www.alibabacloud.com/help/doc-detail/31994.htm)
- [x-oss-copy-source-if-match] only uploadPartCopy api used, default none<br>
If the ETAG value of the source object is equal to the ETAG value provided by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
- [x-oss-copy-source-if-none-match] only uploadPartCopy api used, default none<br>
If the source object has not been modified since the time specified by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
- [x-oss-copy-source-if-unmodified-since] only uploadPartCopy api used, default none<br>
If the time specified by the received parameter is the same as or later than the modification time of the file, the system transfers the file normally, and returns 200 OK; otherwise, the system returns 412 Precondition Failed.
- [x-oss-copy-source-if-modified-since] only uploadPartCopy api used, default none<br>
If the source object has been modified since the time specified by the user, the system performs the Copy Object operation; otherwise, the system returns the 412 Precondition Failed message.
//the other event to cancel, for example: click event
//to cancel upload must use the same client instance
store.cancel();
```
- multipartUploadCopy with versionId
```js
const versionId = 'object versionId';
//start upload
const result = await store.multipartUploadCopy(
'object',
{
sourceKey: 'sourceKey',
sourceBucketName: 'sourceBucketName'
},
{
checkpoint: savedCpt,
progress: function (p, cpt, res) {
console.log(p);
console.log(cpt);
console.log(res.headers['x-oss-request-id']);
},
versionId
}
);
```
### .listParts(name, uploadId[, query, options])
The ListParts command can be used to list all successfully uploaded parts mapped to a specific upload ID, i.e.: those not completed and not
aborted.
parameters:
- name {String} object key
- uploadId {String} upload ID from initMultipartUpload api
- [query] {Object} query parameters
- [max-parts] {Number} The maximum part number in the response of the OSS. default value: 1000.
- [part-number-marker] {Number} Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter.
- [encoding-type] {String} Specify the encoding of the returned content and the encoding type. Optional value: url
- [options] {Object} optional args
- [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)
- uploadId {String} upload ID
- bucket {String} Specify the bucket name.
- name {String} object name
- PartNumberMarker {Number} Starting position of the part numbers in the listing result.
- nextPartNumberMarker {Number} If not all results are returned this time, the response request includes the NextPartNumberMarker element to indicate the value of PartNumberMarker in the next request.
- maxParts {Number} upload ID
- isTruncated {Boolean} Whether the returned result list for List Parts is truncated. The “true” indicates that not all results are returned; “false” indicates that all results are returned.
- parts {Array} The container that saves part information, each in the structure:
- PartNumber {Number} Part number.
- LastModified {Date} Time when a part is uploaded.
- ETag {String} ETag value in the content of the uploaded part.
- Size {Number} Size of the uploaded part.
example:
- List uploaded part
```js
const result = await store.listParts('objcet', 'uploadId', {
'max-parts': 1000
});
console.log(result);
```
### .listUploads(query[, options])
List on-going multipart uploads, i.e.: those not completed and not
aborted.
parameters:
- query {Object} query parameters
- [prefix] {String} the object key prefix
- [max-uploads] {Number} the max uploads to return
- [key-marker] {String} the object key marker, if `upload-id-marker`
is not provided, return uploads with `key > marker`, otherwise
return uploads with `key >= marker && uploadId > id-marker`
- [upload-id-marker] {String} the upload id marker, must be used
client.get('example.txt', { headers: { Range: `bytes=0-${1024 * 1024 * 100}` } }); // Download the first 100MB
```
### ConnectionTimeoutError
The network link timed out. Please check the network status. If there is no problem with the network, please reduce the partSize or increase the timeout.
| BucketNotEmptyError | BucketNotEmpty | 409 | Bucket is not empty | Bucket 不为空 |
| RestoreAlreadyInProgressError | RestoreAlreadyInProgress | 409 | The restore operation is in progress. | restore 操作正在进行中 |
| OperationNotSupportedError | OperationNotSupported | 400 | The operation is not supported for this resource | 该资源暂不支持restore操作 |
| EntityTooLargeError | EntityTooLarge | 400 | Entity too large | 实体过大 |
| EntityTooSmallError | EntityTooSmall | 400 | Entity too small | 实体过小 |
| FileGroupTooLargeError | FileGroupTooLarge | 400 | File group too large | 文件组过大 |
| InvalidLinkNameError | InvalidLinkName | 400 | Link name can't be the same as the object name | Object Link 与指向的 Object 同名 |
| LinkPartNotExistError | LinkPartNotExist | 400 | Can't link to not exists object | Object Link 中指向的 Object 不存在 |
| ObjectLinkTooLargeError | ObjectLinkTooLarge | 400 | Too many links to this object | Object Link 中 Object 个数过多 |
| FieldItemTooLongError | FieldItemTooLong | 400 | Post form fields items too large | Post 请求中表单域过大 |
| FilePartInterityError | FilePartInterity | 400 | File part has changed | 文件 Part 已改变 |
| FilePartNotExistError | FilePartNotExist | 400 | File part not exists | 文件 Part 不存在 |
| FilePartStaleError | FilePartStale | 400 | File part stale | 文件 Part 过时 |
| IncorrectNumberOfFilesInPOSTRequestError | IncorrectNumberOfFilesInPOSTRequest | 400 | Post request contains invalid number of files | Post 请求中文件个数非法 |