O multipart upload do OSS divide objetos grandes em partes para permitir uploads independentes e retomáveis. Após o upload de todas as partes, o OSS as combina em um objeto completo.
Observações de uso
O método multipartUpload divide um objeto em partes e realiza o upload individualmente. Se houver interrupção, apenas as partes com falha ou ausentes serão enviadas novamente.
Utilize o multipart upload para objetos maiores que 100 MB. Para objetos menores, use o upload simples. Em arquivos pequenos, uma configuração inadequada de partSize pode resultar em relatórios de progresso imprecisos.
Caso ocorra um erro ConnectionTimeoutError durante a execução do MultipartUpload, reduza o tamanho da parte, aumente o tempo limite ou reenvie a solicitação. Para investigar a causa raiz, capture o erro ConnectionTimeoutError. Tratamento de tempo limite de conexão de rede.
Os seguintes parâmetros estão disponíveis para multipart upload.
|
Categoria |
Parâmetro |
Descrição |
|
Parâmetros obrigatórios |
name {String} |
O caminho completo do objeto, sem incluir o nome do bucket. |
|
file {String|File} |
O caminho do arquivo local ou arquivo HTML5 a ser enviado. |
|
|
[options] {Object} Parâmetros opcionais |
[checkpoint] {Object} |
Registra o progresso do multipart upload para permitir retomada. Obrigatório quando o upload retomável está ativado. Se uma parte falhar, o OSS continua a partir do progresso registrado. O arquivo de checkpoint é excluído após a conclusão do upload. |
|
[parallel] {Number} |
Número de uploads de partes simultâneos. Padrão: 5. |
|
|
[partSize] {Number} |
Tamanho de cada parte. Valores válidos: 100 KB a 5 GB. Padrão: 1 MB. |
|
|
[progress] {Function} |
Callback de progresso do upload. Pode ser uma função assíncrona. Parâmetros:
|
|
|
[meta] {Object} |
Metadados personalizados. Os cabeçalhos usam o prefixo |
|
|
[mime] {String} |
Cabeçalho de requisição Content-Type. |
|
|
[headers] {Object} |
Outros cabeçalhos HTTP definidos na RFC 2616. Exemplos:
|
Exemplo de multipart upload
O OSS SDK para Node.js não suporta verificação MD5 para multipart upload. Para validar a integridade dos dados, utilize a biblioteca CRC-64 após a conclusão do upload.
O exemplo abaixo utiliza o método multipartUpload para executar um multipart upload:
const OSS = require('ali-oss');
const path = require("path");
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',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: 'yourbucketname',
});
const progress = (p, _checkpoint) => {
// Record the upload progress of the object.
console.log(p);
// Record the checkpoint information about the multipart upload task.
console.log(_checkpoint);
};
const headers = {
// Specify the storage class of the object.
'x-oss-storage-class': 'Standard',
// Specify tags for the object. You can specify multiple tags for the object.
'x-oss-tagging': 'Tag1=1&Tag2=2',
// Specify whether to overwite an existing object with the same name when the multipart upload task is initialized. In this example, this parameter is set to true, which indicates that an existing object with the same name as the object to upload is not overwritten.
'x-oss-forbid-overwrite': 'true'
}
// Start the multipart upload task.
async function multipartUpload() {
try {
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. Do not include the bucket name in the full path.
// By default, if you set this parameter to the name of a local file such as examplefile.txt without specifying the local path, the local file is uploaded from the local path of the project to which the sample program belongs.
const result = await client.multipartUpload('exampledir/exampleobject.txt', path.normalize('D:\\localpath\\examplefile.txt'), {
progress,
// headers,
// Configure the meta parameter to specify metadata for the object. You can call the HeadObject operation to obtain the object metadata.
meta: {
year: 2020,
people: 'test',
},
});
console.log(result);
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
const head = await client.head('exampledir/exampleobject.txt');
console.log(head);
} catch (e) {
// Handle timeout exceptions.
if (e.code === 'ConnectionTimeoutError') {
console.log('TimeoutError');
// do ConnectionTimeoutError operation
}
console.log(e);
}
}
multipartUpload();
O método multipartUpload encapsula as operações initMultipartUpload, uploadPart e completeMultipartUpload. Para realizar o multipart upload passo a passo, chame essas operações diretamente: .initMultipartUpload, .uploadPart e .completeMultipartUpload.
Cancelar um multipart upload
Chame client.abortMultipartUpload para cancelar um multipart upload. O cancelamento invalida o ID de upload e exclui todas as partes já enviadas.
O exemplo a seguir demonstra como cancelar um multipart upload.
const OSS = require("ali-oss");
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",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function abortMultipartUpload() {
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
const name = "exampledir/exampleobject.txt";
// Specify the upload ID. You can obtain the upload ID from the response to the InitiateMultipartUpload operation.
const uploadId = "0004B999EF518A1FE585B0C9360D****";
const result = await client.abortMultipartUpload(name, uploadId);
console.log(result);
}
abortMultipartUpload();
Listar multipart uploads em andamento
Use client.listUploads para listar todos os multipart uploads iniciados que ainda não foram concluídos ou cancelados.
const OSS = require("ali-oss");
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",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function listUploads(query = {}) {
// You can configure the following parameters for query: prefix, marker, delimiter, upload-id-marker, and max-uploads.
const result = await client.listUploads(query);
result.uploads.forEach((upload) => {
// Specify the upload IDs of the multipart upload tasks.
console.log(upload.uploadId);
// Combine all parts into a complete object and specify the full path of the object.
console.log(upload.name);
});
}
const query = {
// Specify the maximum number of multipart upload tasks to return for the current list operation. The default value and the maximum value of max-uploads are both 1000.
"max-uploads": 1000,
};
listUploads(query);
Listar partes enviadas
Execute client.listParts para listar todas as partes enviadas associadas a um ID de upload específico.
const OSS = require("ali-oss");
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",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "yourbucketname",
});
async function listParts() {
const query = {
// Specify the maximum number of parts to return for the current list operation. The default value and the maximum value of max-parts are both 1000.
"max-parts": 1000,
};
let result;
do {
result = await client.listParts(
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
"exampledir/exampleobject.txt",
// Obtain the upload ID from the response to the InitiateMultipartUpload operation. You must obtain the upload ID before you call the CompleteMultipartUpload operation to complete the multipart upload task.
"0004B999EF518A1FE585B0C9360D****",
query
);
// Specify the starting position of the next list operation. Only parts with part numbers greater than the value of this parameter are listed.
query["part-number-marker"] = result.nextPartNumberMarker;
result.parts.forEach((part) => {
console.log(part.PartNumber);
console.log(part.LastModified);
console.log(part.ETag);
console.log(part.Size);
});
} while (result.isTruncated === "true");
}
listParts();
Referências
Código de exemplo completo de multipart upload: GitHub.
-
O método
multipartUploadencapsula as seguintes operações de API: -
Operações de API relacionadas:
AbortMultipartUpload: Cancela uma tarefa de multipart upload em andamento e exclui quaisquer partes já enviadas.
ListParts: Lista todas as partes enviadas com sucesso para uma tarefa de upload específica.
ListMultipartUploads: Lista todas as tarefas de multipart upload atualmente em progresso (iniciadas, mas ainda não concluídas ou abortadas).