Object Storage Service (OSS) provides a multipart upload feature for large objects. This feature splits a large object into multiple parts that can be uploaded independently. After all parts are uploaded, OSS combines them into a single, complete object.
Background information
The multipartUpload method is designed for large objects. It splits an object into parts and uploads them individually. If an upload is interrupted, you can resume it, and only the failed or missing parts will be re-uploaded, saving time and bandwidth.
Use multipart upload for objects larger than 100 MB. For objects smaller than 100 MB, a simple upload is more efficient and recommended. Using multipart upload for small files with an improper partSize may lead to inaccurate progress reporting.
If the ConnectionTimeoutError error occurs when you use the MultipartUpload method, you need to fix the error. You can reduce the part size, extend the timeout period, or resend the request. You can also capture the ConnectionTimeoutError error and fix the error based on the cause. For more information, see Network connection timeout handling.
The table below outlines the parameters that can be configured during a multipart object upload.
Category | Parameter | Description |
Required parameters | name {String} | The full path of the object. Do not include the bucket name in the path. |
file {String|File} | The path of the local file or HTML5 file that you want to upload. | |
[options] {Object} Optional parameters | [checkpoint] {Object} | The checkpoint file that records the result of the multipart upload task. If you enable resumable upload, you must configure this parameter. The checkpoint file stores the upload progress. If a part fails to be uploaded, OSS can resume the upload of the part based on the progress information recorded in this file. After the local file is uploaded, the file that stores progress information is deleted. |
[parallel] {Number} | The number of parts that can be concurrently uploaded. Default value: 5. Use the default value if you do not have special requirements. | |
[partSize] {Number} | The part size. Valid values: 100 KB to 5 GB. Default value: 1 * 1024 * 1024 (1 MB). Use the default value if you do not have special requirements. | |
[progress] {Function} | The callback function that is used to query the progress of the upload task. The callback function can be an async function. The callback function takes the following parameters:
| |
[meta] {Object} | The user metadata. User metadata headers are prefixed by | |
[mime] {String} | The Content-Type request header. | |
[headers] {Object} | Other headers. For more information, see RFC 2616. Examples:
|
Multipart upload example
OSS SDK for Node.js does not support MD5 verification in multipart upload tasks. If you need to verify data integrity, we recommend that you use the CRC-64 library after the multipart upload task is complete.
The following sample code provides an example on how to use the multipartUpload method to perform multipart upload:
const OSS = require('ali-oss');
const path = require("path");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourbucketname',
});
const progress = (p, _checkpoint) => {
// Record the upload progress of the object.
console.log(p);
// Record the checkpoint information about the multipart upload task.
console.log(_checkpoint);
};
const headers = {
// Specify the storage class of the object.
'x-oss-storage-class': 'Standard',
// Specify tags for the object. You can specify multiple tags for the object.
'x-oss-tagging': 'Tag1=1&Tag2=2',
// Specify whether to overwite an existing object with the same name when the multipart upload task is initialized. In this example, this parameter is set to true, which indicates that an existing object with the same name as the object to upload is not overwritten.
'x-oss-forbid-overwrite': 'true'
}
// Start the multipart upload task.
async function multipartUpload() {
try {
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. Do not include the bucket name in the full path.
// By default, if you set this parameter to the name of a local file such as examplefile.txt without specifying the local path, the local file is uploaded from the local path of the project to which the sample program belongs.
const result = await client.multipartUpload('exampledir/exampleobject.txt', path.normalize('D:\\localpath\\examplefile.txt'), {
progress,
// headers,
// Configure the meta parameter to specify metadata for the object. You can call the HeadObject operation to obtain the object metadata.
meta: {
year: 2020,
people: 'test',
},
});
console.log(result);
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
const head = await client.head('exampledir/exampleobject.txt');
console.log(head);
} catch (e) {
// Handle timeout exceptions.
if (e.code === 'ConnectionTimeoutError') {
console.log('TimeoutError');
// do ConnectionTimeoutError operation
}
console.log(e);
}
}
multipartUpload();The multipartUpload method in the preceding code sample contains the initMultipartUpload, uploadPart, and completeMultipartUpload operations. If you want to perform multipart upload step by step, call the preceding operations in sequence. For more information, see .initMultipartUpload, .uploadPart, and .completeMultipartUpload.
Cancel a multipart upload task
Use the client.abortMultipartUpload method to cancel a multipart upload task. If you cancel a multipart upload task, you cannot use the upload ID to upload parts and the uploaded parts are deleted.
The following sample code provides an example on how to cancel a multipart upload task.
const OSS = require("ali-oss");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "yourregion",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function abortMultipartUpload() {
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
const name = "exampledir/exampleobject.txt";
// Specify the upload ID. You can obtain the upload ID from the response to the InitiateMultipartUpload operation.
const uploadId = "0004B999EF518A1FE585B0C9360D****";
const result = await client.abortMultipartUpload(name, uploadId);
console.log(result);
}
abortMultipartUpload();
List multipart upload tasks
Use the client.listUploads method to list all ongoing multipart upload tasks, which are tasks that have been initiated but are not completed or canceled.
const OSS = require("ali-oss");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "yourregion",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function listUploads(query = {}) {
// You can configure the following parameters for query: prefix, marker, delimiter, upload-id-marker, and max-uploads.
const result = await client.listUploads(query);
result.uploads.forEach((upload) => {
// Specify the upload IDs of the multipart upload tasks.
console.log(upload.uploadId);
// Combine all parts into a complete object and specify the full path of the object.
console.log(upload.name);
});
}
const query = {
// Specify the maximum number of multipart upload tasks to return for the current list operation. The default value and the maximum value of max-uploads are both 1000.
"max-uploads": 1000,
};
listUploads(query);
List uploaded parts
Use the client.listParts method to list all parts that are uploaded by using the multipart upload task with the specified upload ID.
const OSS = require("ali-oss");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "yourregion",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function listParts() {
const query = {
// Specify the maximum number of parts to return for the current list operation. The default value and the maximum value of max-parts are both 1000.
"max-parts": 1000,
};
let result;
do {
result = await client.listParts(
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
"exampledir/exampleobject.txt",
// Obtain the upload ID from the response to the InitiateMultipartUpload operation. You must obtain the upload ID before you call the CompleteMultipartUpload operation to complete the multipart upload task.
"0004B999EF518A1FE585B0C9360D****",
query
);
// Specify the starting position of the next list operation. Only parts with part numbers greater than the value of this parameter are listed.
query["part-number-marker"] = result.nextPartNumberMarker;
result.parts.forEach((part) => {
console.log(part.PartNumber);
console.log(part.LastModified);
console.log(part.ETag);
console.log(part.Size);
});
} while (result.isTruncated === "true");
}
listParts();References
For the complete sample code for multipart upload, visit GitHub.
The high-level
multipartUploadmethod in the OSS SDK for Node.js internally wraps the following three low-level API operations:For more details on the underlying API operations, see the following topics:
AbortMultipartUpload: Cancels an in-progress multipart upload task and deletes any uploaded parts.
ListParts: Lists all successfully uploaded parts for a specific upload task.
ListMultipartUploads: Lists all multipart upload tasks that are currently in progress (initiated but not yet completed or aborted).