Este tópico descreve como usar o OSS SDK for Browser.js para executar operações como upload, download e consulta de objetos.
Pré-requisitos
O OSS SDK for Browser.js está instalado. Para mais informações, consulte Installation.
Uma regra de compartilhamento de recursos entre origens (CORS) está configurada para o bucket. Para mais informações, consulte Installation.
Notas de uso
O OSS SDK for Browser.js não oferece suporte a operações relacionadas a buckets em navegadores. Ele suporta apenas operações relacionadas a objetos, como PutObject e GetObject.
-
Na maioria dos casos, o OSS SDK for Browser.js é usado em navegadores. Para evitar a exposição do seu par de AccessKey, recomendamos usar credenciais de acesso temporárias obtidas do Security Token Service (STS) para acessar o OSS.
As credenciais de acesso temporárias consistem em um par de AccessKey e um token de segurança. O par de AccessKey é composto por um AccessKeyID e um AccessKeySecret. Para mais informações sobre como obter credenciais de acesso temporárias, consulte Use STS for temporary access authorization.
Operações comuns
Esta seção descreve as operações comuns com o OSS SDK for Browser.js.
Criar um servidor STS e obter informações de autorização temporária a partir de um cliente
-
Crie um servidor STS.
Para ajudar na criação de um servidor STS, o OSS fornece SDKs nas seguintes linguagens:
ImportanteOs exemplos acima servem apenas como referência. No ambiente de produção, desenvolva o código necessário para autenticação e outros recursos.
-
Envie requisições ao servidor STS a partir do navegador para obter as informações de autorização temporária do STS.
<!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>
Fazer upload de objetos
Chame a interface multipartUpload para fazer upload de um arquivo.
<!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>
Baixar objetos
O OSS gera uma URL assinada como link de download de um objeto. Use esse link para baixar o objeto.
<!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>
Listar objetos
O código de exemplo a seguir demonstra como listar objetos:
<!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>