Object Storage Service (OSS) provides a multipart upload feature that splits a large file, or Object, into multiple parts. You can upload these parts independently. After all parts are uploaded, you can call the CompleteMultipartUpload operation to combine them into a single Object. This process allows for resumable uploads.
Precautions
Before you perform a multipart upload, make sure that you understand the feature. For more information, see Multipart upload.
If you use a packaging tool such as webpack or browserify, install the Browser.js software development kit (SDK) by running the npm install ali-oss command.
Accessing OSS from a browser involves cross-origin requests. If you do not configure cross-origin rules, the browser denies these requests. To access OSS from a browser, you must configure cross-origin rules in OSS. For more information, see Preparations.
The Browser.js SDK is typically used in browser environments. To avoid exposing the AccessKey pair (AccessKey ID and AccessKey secret) of your Alibaba Cloud account, use temporary access credentials to perform OSS operations.
Temporary access credentials include a temporary AccessKey pair (AccessKey ID and AccessKey secret) and a security token. For more information about how to obtain temporary access credentials, see Grant access (Browser.js SDK).
Complete example code for multipart upload
To upload a large file, you can use the MultipartUpload operation. This operation splits the file into multiple data blocks, or parts, that you can upload separately. If some parts fail to upload, OSS saves the progress. You need to re-upload only the failed parts, not the entire file.
For files larger than 100 MB, use multipart upload. Resumable uploads and retries help increase the success rate. If you use multipart upload for a file smaller than 100 MB with an improper `partSize`, the upload progress might not be completely displayed. For files smaller than 100 MB, use simple upload.
The following code shows how to use multipart upload to upload a file named exampleobject.txt to the examplebucket bucket.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="submit">Upload</button>
<input id="file" type="file" />
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: "yourRegion",
authorizationV4: true,
// The temporary AccessKey ID and AccessKey secret obtained from STS.
accessKeyId: "yourAccessKeyId",
accessKeySecret: "yourAccessKeySecret",
// The security token obtained from STS.
stsToken: "yourSecurityToken",
// Specify the bucket name, for example, examplebucket.
bucket: "examplebucket",
});
const headers = {
// Specify the caching behavior of the web page when the object is downloaded.
"Cache-Control": "no-cache",
// Specify the name of the object when it is downloaded.
"Content-Disposition": "example.txt",
// Specify the expiration time in milliseconds.
Expires: "1000",
// Specify the storage class of the object.
"x-oss-storage-class": "Standard",
// Specify tags for the object. You can specify multiple tags.
"x-oss-tagging": "Tag1=1&Tag2=2",
// Specify whether to overwrite an object that has the same name when you initialize a multipart upload. A value of true indicates that overwriting is prohibited.
"x-oss-forbid-overwrite": "true",
};
// Specify the name of the object to be uploaded to examplebucket, for example, exampleobject.txt.
const name = "exampleobject.txt";
// Get the DOM.
const submit = document.getElementById("submit");
const options = {
// Obtain the multipart upload progress, checkpoint, and return value.
progress: (p, cpt, res) => {
console.log(p);
},
// Set the number of parts to upload concurrently.
parallel: 4,
// Set the part size. The default value is 1 MB. The minimum value is 100 KB. The maximum value is 5 GB. The size of the last part can be smaller than 100 KB.
partSize: 1024 * 1024,
// headers,
// Custom metadata. You can obtain the metadata of the object by calling the HeadObject operation.
meta: { year: 2020, people: "test" },
mime: "text/plain",
};
// Add a listener to the button.
submit.addEventListener("click", async () => {
try {
const data = document.getElementById("file").files[0];
// Perform multipart upload.
const res = await client.multipartUpload(name, data, {
...options,
// Set the upload callback.
// If no callback server is involved, delete the callback settings.
callback: {
// Set the server address for the callback request.
url: "http://examplebucket.aliyuncs.com:23450",
// Set the Host value in the header of the callback request. This is the Host value configured on your server.
host: "yourHost",
/* eslint no-template-curly-in-string: [0] */
// Set the value of the request body when a callback is initiated.
body: "bucket=${bucket}&object=${object}&var1=${x:var1}",
// Set the Content-Type of the callback request.
contentType: "application/x-www-form-urlencoded",
customValue: {
// Set custom parameters for the callback request.
var1: "value1",
var2: "value2",
},
},
});
console.log(res);
} catch (err) {
console.log(err);
}
});
</script>
</body>
</html>
If a ConnectionTimeoutError occurs when you call the MultipartUpload operation, you must handle the timeout. For example, you can reduce the part size, increase the timeout period, retry the request, or catch the ConnectionTimeoutError. For more information, see Handle network errors.
Cancel a multipart upload event
You can call the client.abortMultipartUpload method to cancel a multipart upload event. After an event is canceled, you cannot use its uploadId for any operations, and the uploaded part data is deleted.
The following code shows how to cancel a multipart upload event:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="submit">Upload</button>
<button id="abort">Abort</button>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: "yourRegion",
authorizationV4: true,
// The temporary AccessKey ID and AccessKey secret obtained from STS.
accessKeyId: "yourAccessKeyId",
accessKeySecret: "yourAccessKeySecret",
// The security token obtained from STS.
stsToken: "yourSecurityToken",
// Specify the bucket name, for example, examplebucket.
bucket: "examplebucket",
});
// Generate a 100 MB file for multipart upload.
const fileContent = Array(1024 * 1024 * 100)
.fill("a")
.join("");
const file = new File([fileContent], "multipart-upload-file");
// Set the name of the object to be uploaded to examplebucket, for example, exampleobject.txt.
const name = "exampleobject.txt";
// Set the checkpoint.
let abortCheckpoint;
// Get the DOM.
const submit = document.getElementById("submit");
const abort = document.getElementById("abort");
// Add a listener to the upload button. After you click Upload, multipart upload starts.
submit.addEventListener("click", async () => {
try {
const res = await client.multipartUpload(name, file, {
progress: (p, cpt, res) => {
// Assign a value to the checkpoint.
abortCheckpoint = cpt;
// Obtain the upload progress.
console.log(p);
},
});
} catch (err) {
console.log(err);
}
});
// Add a listener to the abort button.
abort.addEventListener("click", () => {
// Abort the multipart upload.
client.abortMultipartUpload(
abortCheckpoint.name,
abortCheckpoint.uploadId
);
});
</script>
</body>
</html>
List uploaded parts
You can call the client.listParts method to list all successfully uploaded parts for a specified uploadId.
The following code shows how to list uploaded parts:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="submit">Upload</button>
<button id="check">List uploaded parts</button>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey ID and AccessKey secret obtained from STS.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name, for example, examplebucket.
bucket: "examplebucket",
});
// Generate a 100 MB file for multipart upload.
const fileContent = Array(1024 * 1024 * 100)
.fill("a")
.join("");
const file = new File([fileContent], "multipart-upload-file");
// Set the name of the object to be uploaded to examplebucket, for example, exampleobject.txt.
const name = "exampleobject.txt";
// Set the checkpoint.
let abortCheckpoint;
// Get the DOM.
const submit = document.getElementById("submit");
const check = document.getElementById("check");
// Add a listener to the button.
submit.addEventListener("click", async () => {
try {
const res = await client.multipartUpload(name, file, {
progress: (p, cpt, res) => {
// Assign a value to the checkpoint.
abortCheckpoint = cpt;
// Obtain the upload progress.
console.log("progress=====", p);
},
});
} catch (err) {
console.log(err);
}
});
// Add a listener to the button.
check.addEventListener("click", async () => {
// List the uploaded parts.
const result = await client.listParts(name, abortCheckpoint.uploadId);
console.log(result);
});
</script>
</body>
</html>
List multipart upload events
You can call the client.listUploads method to list all in-progress multipart upload events. In-progress events are events that have been initiated but not yet completed or canceled.
The following code shows how to list multipart upload events:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="check">List multipart upload events</button>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey ID and AccessKey secret obtained from STS.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name, for example, examplebucket.
bucket: "examplebucket",
});
// Get the DOM.
const check = document.getElementById("check");
// Add a listener to the button.
check.addEventListener("click", async () => {
// Obtain all multipart upload events that are initiated but not completed or canceled.
const result = await client.listUploads({ "max-uploads": 100 });
console.log("uploads", result.uploads);
});
</script>
</body>
</html>References
For the complete sample code for multipart upload, see GitHub example.
The
multipartUploadmethod that is called for multipart upload in the Browser.js SDK encapsulates the following three API operations:For more information about the API operation to initialize a multipart upload event, see InitiateMultipartUpload.
For more information about the API operation to upload a part, see UploadPart.
For more information about the API operation to complete a multipart upload, see CompleteMultipartUpload.
For more information about the API operation to cancel a multipart upload event, see AbortMultipartUpload.
For more information about the API operation to list uploaded parts, see ListParts.
For more information about the API operation to list all in-progress multipart upload events, see ListMultipartUploads.
FAQ
How do I resolve the "PLease set the etag of expose-headers in Oss." error?
Cause
Cross-origin resource sharing (CORS) is not correctly configured.
Solution
Configure CORS for the current bucket. When you configure CORS rules, you must expose common headers such as x-oss-request-id and ETag. For more information, see Configure CORS.
How do I resolve the "The operation is not supported for this resource." error?
Cause
You set the object storage class when you called the CompleteMultipartUpload operation.
Solution
You cannot set the object storage class when you call CompleteMultipartUpload. To specify the object storage class for a multipart upload, you must set it when you call InitiateMultipartUpload.