Este tópico descreve os casos de uso em navegadores.
Pré-requisitos
Configure as regras de cross-domain do bucket. Para mais informações, consulte Preparações.
Crie um servidor Security Token Service (STS) e obtenha as informações de autorização temporária no cliente. Para mais detalhes, consulte Criar um servidor STS e obter informações de autorização temporária no cliente.
Navegadores compatíveis
O Browser.js SDK é compatível com as seguintes versões de navegadores:
-
IE 10 ou superior e Edge
ImportanteImporte uma biblioteca de promise antes de usar o Browser.js SDK no IE.
O Browser.js SDK usa a File API para operações de arquivo, o que pode causar problemas em versões antigas do navegador. Utilize plug-ins de terceiros para chamar as APIs do OSS em operações como upload e download de arquivos. Para ver um exemplo, consulte Práticas de upload direto via web.
Versões principais do Chrome, Firefox e Safari
Navegadores padrão nas versões principais do Android, iOS e Windows Phone
Fazer upload de um arquivo pelo navegador
O código de exemplo a seguir demonstra como fazer upload de um arquivo diretamente pelo navegador. Este exemplo usa os estilos do Bootstrap.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<link
rel="stylesheet"
href="https://cdn.bootcss.com/twitter-bootstrap/2.3.2/css/bootstrap.min.css"
/>
<style>
.form-group {
margin: 10px;
}
</style>
</head>
<body style="padding: 100px">
<div class="form-group">
<!-- // Select the file to upload. -->
<label>Select file</label>
<input type="file" id="file" />
</div>
<div class="form-group">
<!-- // Specify the name of the file to upload to OSS. -->
<label>Store as</label>
<input type="text" class="form-control" id="object-key-file" value="" />
</div>
<div class="form-group">
<!-- // Upload the file. -->
<input
type="button"
class="btn btn-primary"
id="file-button"
value="Upload"
/>
</div>
<div class="form-group">
<!-- // Show the upload progress. -->
<div class="progress">
<div
id="progress-bar"
class="progress-bar"
role="progressbar"
aria-valuenow="0"
aria-valuemin="0"
aria-valuemax="100"
style="min-width: 2em"
>
0%
</div>
</div>
</div>
<!--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">
// Specify the URL of your authorization server. For example, http://127.0.0.1:8000/sts.
const appServer = "yourStsServer";
// Specify the bucket name. For example, examplebucket.
const bucket = "examplebucket";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
const region = "oss-cn-hangzhou";
const urllib = OSS.urllib;
const applyTokenDo = function (func) {
const url = appServer;
return urllib
.request(url, {
method: "GET",
})
.then(function (result) {
const creds = JSON.parse(result.data);
// Create an OSS client using the temporary access credentials.
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: region,
authorizationV4: true,
accessKeyId: creds.AccessKeyId,
accessKeySecret: creds.AccessKeySecret,
stsToken: creds.SecurityToken,
bucket: bucket,
});
return func(client);
});
};
let currentCheckpoint;
const progress = async function progress(p, checkpoint) {
currentCheckpoint = checkpoint;
const bar = document.getElementById("progress-bar");
bar.style.width = `${Math.floor(p * 100)}%`;
bar.innerHTML = `${Math.floor(p * 100)}%`;
};
let uploadFileClient;
const uploadFile = function (client) {
if (!uploadFileClient || Object.keys(uploadFileClient).length === 0) {
uploadFileClient = client;
}
const file = document.getElementById("file").files[0];
const key =
document.getElementById("object-key-file").value.trim() || "object";
console.log(`${file.name} => ${key}`);
// Use multipartUpload to upload the selected file and use the progress parameter to set the progress bar.
const options = {
progress,
partSize: 100 * 1024,
meta: {
year: 2017,
people: "test",
},
};
return client
.multipartUpload(key, file, options)
.then((res) => {
console.log("upload success: %j", res);
currentCheckpoint = null;
uploadFileClient = null;
})
.catch((err) => {
if (uploadFileClient && uploadFileClient.isCancel()) {
console.log("stop-upload!");
} else {
console.error(err);
}
});
};
window.onload = function () {
document.getElementById("file-button").onclick = function () {
applyTokenDo(uploadFile);
};
};
</script>
</body>
</html>
Referências
Para obter o código de exemplo completo para aplicações de navegador, consulte o exemplo no GitHub.