O OSS não permite renomear objetos diretamente. Para renomear um objeto, copie-o e exclua o original: chame CopyObject para criar um novo objeto com o nome desejado e, em seguida, chame DeleteObject para remover o objeto source.
Código de exemplo
O código de exemplo a seguir mostra como renomear um objeto chamado srcobject.txt para destobject.txt no examplebucket.
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: 'oss-cn-hangzhou',
// Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket',
})
async function renameObject() {
try {
// Copy the source object 'srcobject.txt' to a new destination object 'destobject.txt'.
const r = await client.copy('destobject.txt', 'srcobject.txt');
console.log ('Copied', r);
// Delete srcobject.txt.
const deleteResult = await client.delete('srcobject.txt');
console.log(deleteResult);
} catch (e) {
console.log(e);
}
}
renameObject();
Nota
Para renomear diretórios, use a mesma abordagem de cópia e exclusão, aplicada recursivamente a todos os objetos e subdiretórios.
Referências
Para obter mais informações sobre as operações de API usadas para renomear um objeto, consulte CopyObject e DeleteObject.