This topic describes how to use OSS SDK for Browser.js to perform operations such as uploading, downloading, and querying objects.
Prerequisites
-
OSS SDK for Browser.js is installed. For more information, see Installation.
-
A cross-origin resource sharing (CORS) rule is configured for the bucket. For more information, see Installation.
Usage notes
-
OSS SDK for Browser.js does not support bucket-related operations in a browser. OSS SDK for Browser.js supports only object-related operations, such as PutObject and GetObject.
-
In most cases, OSS SDK for Browser.js is used in browsers. To prevent your AccessKey pair from being exposed, we recommend that you use temporary access credentials obtained from Security Token Service (STS) to access OSS.
The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information about how to obtain temporary access credentials, see Use STS for temporary access authorization.
Common operations
This section describes common operations using OSS SDK for Browser.js.
Build an STS server and obtain temporary authorization information from a client
-
Build an STS server.
To help you build an STS server, OSS provides OSS SDKs in the following languages:
ImportantThe preceding demos are for reference only. You must develop required code for authentication and other features in the production environment.
-
Initiate requests to the STS server from a browser to obtain the STS temporary authorization information.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script> <script type="text/javascript"> // OSS.urllib is the logic encapsulated in the SDK for sending requests. You can use any request library to send requests to your_sts_server. // Replace your_sts_server with the IP address or domain name of the STS server that you set up in Step 1. OSS.urllib.request( "your_sts_server", { method: "GET" }, (err, response) => { if (err) { return alert(err); } try { result = JSON.parse(response); } catch (e) { errmsg = "parse sts response info error: " + e.message; return alert(errmsg); } console.log(result); } ); </script> </body> </html>
Upload objects
You can call the multipartUpload interface to upload a file.
<!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>
Download objects
OSS generates a signed URL as the download link of an object. You can use the link to download the object.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<!-- 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 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",
authorizationV4: true,
// Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret.
accessKeyId: "yourAccessKeyId",
accessKeySecret: "yourAccessKeySecret",
// Specify the security token obtained from STS.
stsToken: "yoursecurityToken",
// Specify the name of the bucket.
bucket: "examplebucket",
});
// Set the response header to automatically download an object by using the URL, and set the name of the local file after the object is downloaded.
const filename = "examplefile.txt";
const response = {
"content-disposition": `attachment; filename=${encodeURIComponent(
filename
)}`,
};
// Specify the full path of the object. Do not include the bucket name in the full path.
const url = client.signatureUrl("exampleobject.txt", { response });
console.log(url);
</script>
</body>
</html>
List objects
The following sample code provides an example on how to list objects:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
</head>
<body>
<script>
const client = new OSS({
// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: "yourRegion",
authorizationV4: true,
// The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The security token (SecurityToken) obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
});
async function list(dir) {
try {
// By default, a maximum of 1,000 files are returned.
let result = await client.list();
console.log(result);
// Continue to obtain the file list starting from the file that follows the last file read in the previous list operation.
if (result.isTruncated) {
result = await client.list({ marker: result.nextMarker });
}
// List files that have the prefix 'ex'.
result = await client.list({
prefix: "ex",
});
console.log(result);
// List files that have the prefix 'ex' and whose names come after 'example' in alphabetical order.
result = await client.list({
prefix: "ex",
marker: "example",
});
console.log(result);
} catch (e) {
console.log(e);
}
}
list();
</script>
</body>
</html>