Por padrão, ao fazer upload de um objeto com o mesmo nome de um objeto existente, o novo objeto substitui o anterior. Este tópico descreve como configurar o cabeçalho de solicitação x-oss-forbid-overwrite para evitar que objetos existentes sejam substituídos por objetos com nomes idênticos durante operações de cópia, upload simples ou multipart upload.
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ê tentar acessar um bucket do OSS pelo navegador sem regras CORS configuradas, o navegador rejeitará a solicitação. Portanto, configure regras CORS no bucket para permitir o acesso via navegador. Para mais informações, consulte Instalação.
-
O OSS SDK for Browser.js é usado principalmente em navegadores. Para evitar a exposição do seu par de AccessKey, use credenciais de acesso temporárias obtidas pelo Security Token Service (STS) para acessar o OSS.
As credenciais de acesso temporárias consistem em um par de AccessKey e um token de segurança. O par de AccessKey inclui um AccessKey ID e um AccessKey secret. Para saber como obter essas credenciais, consulte Usar STS para autorização de acesso temporário.
Upload simples
O código a seguir mostra como impedir a substituição de um objeto com o mesmo nome durante um upload simples:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id='upload'>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 bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary 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. Example: examplebucket.
bucket: "examplebucket",
});
const upload = document.getElementById('upload')
// Specify the local file to upload.
const fileContent = Array(1024 * 1024 * 10).fill('a').join('')
const fileName = 'example.txt'
const file = new Blob([fileContent])
// Specify whether to overwrite an object that has the same name. In this example, this parameter is set to true. This indicates that an object that has the same name cannot be overwritten. If an object with the same name exists, an error is reported.
const headers = {
'x-oss-forbid-overwrite': true
}
upload.addEventListener('click', () => {
// Upload the file.
client.put(fileName, file, { headers }).then(r => console.log(r))
})
</script>
</body>
</html>
Copiar um arquivo
O código a seguir mostra como impedir a substituição de um objeto com o mesmo nome ao copiar um objeto:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id='upload'>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 bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary 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. Example: examplebucket.
bucket: "examplebucket",
});
const upload = document.getElementById('upload')
// Specify the file to copy.
const fileContent = Array(1024 * 1024 * 5).fill('a').join('')
const fileName = 'example.txt'
const file = new Blob([fileContent])
// Specify whether to overwrite an object that has the same name during the copy operation. In this example, this parameter is set to true. This indicates that an object that has the same name cannot be overwritten. If an object with the same name exists, an error is reported.
const headers = {
'x-oss-forbid-overwrite': true
}
upload.addEventListener('click', () => {
// Copy the file.
// Set the name of the destination file to dest.txt.
client.copy("dest.txt",fileName,{headers}).then(r=>console.log(r))
})
</script>
</body>
</html>
Multipart upload
O código a seguir mostra como impedir a substituição de um objeto com o mesmo nome durante um multipart upload:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="upload">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 bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary 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. Example: examplebucket.
bucket: "examplebucket",
});
const upload = document.getElementById("upload");
// Specify the file to upload.
const fileContent = Array(1024 * 1024 * 5)
.fill("a")
.join("");
const fileName = "src.txt";
const file = new Blob([fileContent]);
// Specify whether to overwrite an object that has the same name. In this example, this parameter is set to true. This indicates that an object that has the same name cannot be overwritten. If an object with the same name exists, an error is reported.
const headers = {
"x-oss-forbid-overwrite": true,
};
upload.addEventListener("click", () => {
// Perform a multipart upload.
client
.multipartUpload("dest.txt", file, { headers })
.then((r) => console.log(r));
});
</script>
</body>
</html>
Referências
Para mais informações sobre a operação de API de upload simples, consulte PutObject.
Para mais informações sobre a operação de API de cópia de objetos, consulte CopyObject.
-
O método
multipartUploadno Browser.js SDK executa multipart uploads e encapsula as três operações de API a seguir:Para iniciar um multipart upload, consulte InitiateMultipartUpload.
Para enviar partes, consulte UploadPart.
Para concluir um multipart upload, consulte CompleteMultipartUpload.