Por padrão, se você fizer upload de um objeto com o mesmo nome de um objeto existente, o objeto existente será sobrescrito. Este tópico descreve como configurar o cabeçalho de solicitação x-oss-forbid-overwrite para impedir que objetos existentes sejam sobrescritos por objetos com o mesmo nome durante a cópia de objetos, upload simples ou multipart upload.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para obter mais informações sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).
Código de exemplo
O código de exemplo a seguir mostra como impedir que objetos existentes sejam sobrescritos por objetos com o mesmo nome ao realizar um upload simples:
package main
import (
"log"
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// 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 cn-hangzhou. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of your bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Specify whether to overwrite an existing object with the same name.
// By default, if you do not specify oss.ForbidOverWrite, an object that has the same name is overwritten.
// If you set oss.ForbidOverWrite to false, an object that has the same name is overwritten.
// If you set oss.ForbidOverWrite to true, an object that has the same name is not overwritten. If such an object exists, an error is reported.
forbidWrite := oss.ForbidOverWrite(true)
// Upload the string.
// Specify the full path of the object. Do not include the bucket name in the full path.
objectName := "yourObjectName"
objectValue := "yourObjectValue"
err = bucket.PutObject(objectName, strings.NewReader(objectValue), forbidWrite)
if err != nil {
log.Fatalf("Failed to upload object '%s': %v", objectName, err)
}
log.Printf("Successfully uploaded object '%s' with value '%s'", objectName, objectValue)
}
Cenários comuns
Impedir sobrescritas em uma tarefa de cópia de objeto
Impedir sobrescritas em uma tarefa de multipart upload
Referências
Para obter mais informações sobre a operação de API que você pode chamar para realizar um upload simples, consulte PutObject.
Para obter mais informações sobre a operação de API que você pode chamar para copiar um objeto, consulte CopyObject.
Para obter mais informações sobre as operações de API que você pode chamar para realizar um multipart upload, consulte InitiateMultipartUpload e CompleteMultipartUpload.