O Object Storage Service (OSS) oferece um recurso de upload multipartido que divide um arquivo grande, ou objeto, em várias partes. Você pode enviar essas partes independentemente. Após enviar todas as partes, chame a operação CompleteMultipartUpload para combiná-las em um único objeto. Esse processo permite retomar uploads interrompidos.
Precauções
Antes de iniciar um upload multipartido, certifique-se de compreender o recurso. Para mais informações, consulte Upload multipartido.
Se você utilizar ferramentas de empacotamento como webpack ou browserify, instale o kit de desenvolvimento de software (SDK) Browser.js executando o comando npm install ali-oss.
O acesso ao OSS pelo navegador envolve requisições de origem cruzada. Se você não configurar as regras de CORS, o navegador bloqueará essas requisições. Para acessar o OSS via navegador, configure as regras de CORS no OSS. Para mais detalhes, consulte Preparações.
-
O Browser.js SDK é geralmente usado em ambientes de navegador. Para evitar a exposição do par AccessKey (AccessKey ID e AccessKey secret) da sua conta Alibaba Cloud, use credenciais de acesso temporárias nas operações do OSS.
As credenciais de acesso temporárias incluem um par AccessKey temporário (AccessKey ID e AccessKey secret) e um token de segurança. Para saber como obter essas credenciais, consulte Conceder acesso (Browser.js SDK).
Código de exemplo completo para upload multipartido
Para enviar arquivos grandes, use a operação MultipartUpload. Essa operação fragmenta o arquivo em vários blocos de dados, ou partes, que você pode enviar separadamente. Se alguma parte falhar, o OSS manterá o progresso salvo. Assim, basta reenviar apenas as partes com erro, sem precisar reiniciar todo o arquivo.
Use o upload multipartido para arquivos maiores que 100 MB. A capacidade de retomada e as tentativas automáticas aumentam a taxa de sucesso. Se você usar esse método para arquivos menores que 100 MB com um partSize inadequado, a barra de progresso pode não ser exibida corretamente. Para arquivos abaixo de 100 MB, prefira o upload simples.
O código abaixo demonstra como usar o upload multipartido para enviar um arquivo chamado exampleobject.txt para o bucket examplebucket.
<!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>
Se ocorrer um erro ConnectionTimeoutError durante a chamada da operação MultipartUpload, trate o tempo limite adequadamente. Algumas estratégias incluem reduzir o tamanho da parte, aumentar o período de timeout, tentar novamente a requisição ou capturar a exceção ConnectionTimeoutError. Para mais orientações, consulte Tratar erros de rede.
Cancelar um evento de upload multipartido
Use o método client.abortMultipartUpload para cancelar um evento de upload multipartido. Após o cancelamento, o uploadId associado torna-se inválido para qualquer operação e os dados das partes já enviadas são excluídos.
O exemplo a seguir mostra como cancelar um evento de upload multipartido:
<!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>
Listar partes enviadas
Chame o método client.listParts para listar todas as partes enviadas com sucesso associadas a um determinado uploadId.
Veja abaixo como listar as partes já enviadas:
<!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>
Listar eventos de upload multipartido
O método client.listUploads lista todos os eventos de upload multipartido em andamento. Eventos em andamento são aqueles iniciados, mas ainda não concluídos ou cancelados.
O código a seguir ilustra como listar esses eventos:
<!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>
Referências
Para acessar o código de exemplo completo sobre upload multipartido, consulte o exemplo no GitHub.
-
No Browser.js SDK, o método
multipartUploadencapsula as três operações de API listadas abaixo:Para iniciar um evento de upload multipartido, consulte InitiateMultipartUpload.
Para enviar uma parte específica, consulte UploadPart.
Para concluir o upload multipartido, consulte CompleteMultipartUpload.
Para cancelar um evento de upload multipartido, consulte AbortMultipartUpload.
Para listar partes enviadas, consulte ListParts.
Para listar todos os eventos de upload multipartido em andamento, consulte ListMultipartUploads.
Perguntas frequentes
Como resolver o erro "PLease set the etag of expose-headers in Oss."?
-
Causa
O compartilhamento de recursos de origem cruzada (CORS) não está configurado corretamente.
-
Solução
Configure o CORS para o bucket atual. Ao definir as regras de CORS, exponha os cabeçalhos comuns, como x-oss-request-id e ETag. Para instruções detalhadas, consulte Configurar CORS.
Como resolver o erro "The operation is not supported for this resource."?
-
Causa
Você definiu a classe de armazenamento do objeto durante a chamada da operação CompleteMultipartUpload.
-
Solução
Não é possível definir a classe de armazenamento do objeto na operação CompleteMultipartUpload. Para especificar essa classe em um upload multipartido, defina-a previamente ao chamar InitiateMultipartUpload.