O upload retomável permite especificar um checkpoint antes de enviar um arquivo para o OSS. Se a transferência for interrompida por falha de rede ou erro no programa, você poderá retomá-la a partir do checkpoint salvo.
Observações de uso
Ao usar ferramentas de empacotamento como Webpack e Browserify, instale o OSS SDK for Browser.js executando o comando npm install ali-oss.
Se você acessar um bucket do OSS diretamente pelo navegador sem regras de CORS configuradas, o navegador rejeitará a solicitação. Portanto, configure as regras de CORS no bucket antes de acessá-lo via navegador. Para mais informações, consulte Instalação.
-
Como o OSS SDK for Browser.js é usado principalmente em navegadores, evite expor seu par de AccessKey. Recomendamos usar credenciais de acesso temporárias obtidas pelo Security Token Service (STS) para acessar o OSS.
Essas credenciais temporárias incluem um par de AccessKey e um token de segurança. O par de AccessKey consiste em um AccessKey ID e um AccessKey secret. Para saber como obter credenciais de acesso temporárias, consulte Usar STS para autorização de acesso temporário.
Código de exemplo
O código abaixo demonstra um upload retomável.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="submit">Upload</button>
<button id="pause">Pause</button>
<button id="resume">Resume Upload</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({
// Set yourRegion to the region where the bucket is located. For example, if the region is China (Hangzhou), 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",
});
// Generate a 100 MB file for the resumable upload.
const fileContent = Array(1024 * 1024 * 100)
.fill("a")
.join("");
const file = new File([fileContent], "multipart-upload-file");
// The full path of the object. Example: exampledir/exampleobject.txt.
const name = "test.txt";
// Define the checkpoint.
let abortCheckpoint;
// Get the upload and pause DOM elements.
const submit = document.getElementById("submit");
const pause = document.getElementById("pause");
// Get the resume DOM element.
const resume = document.getElementById("resume");
// Add a listener to the upload button. The upload starts when you click Upload.
submit.addEventListener("click", () => {
client
.multipartUpload(name, file, {
progress: (p, cpt, res) => {
// Assign a value to the checkpoint.
abortCheckpoint = cpt;
console.log(abortCheckpoint);
// Obtain the upload progress.
console.log(p * 100);
},
})
.then((r) => console.log(r));
});
// Add a listener to the pause button.
pause.addEventListener("click", () => {
// Pause the upload.
client.cancel();
});
const resumeUpload = async () => {
// Set the number of retries to five.
try {
const result = await client.multipartUpload(name, file, {
checkpoint: abortCheckpoint,
progress: (p, cpt, res) => {
// To implement resumable upload, you can save the checkpoint information during the upload. If an upload error occurs, pass the saved checkpoint as a parameter to multipartUpload. The upload then resumes from the point of the last failure.
abortCheckpoint = cpt;
// Obtain the upload progress.
console.log(p);
},
});
console.log(result);
} catch (e) {
console.log(e);
}
};
// Add a listener to the resume button. The upload continues when you click Resume Upload.
resume.addEventListener("click", async () => {
await resumeUpload();
});
</script>
</body>
</html>
Referências
Para obter o código completo de uploads retomáveis, consulte o exemplo no GitHub.