Este tópico descreve como fazer upload de objetos para um bucket com versionamento habilitado.
Observações
Neste tópico, utiliza-se o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configure access credentials.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de um domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para fazer upload de um objeto, você precisa ter a permissão
oss:PutObject. Para mais informações, consulte Grant a custom policy.
Código de exemplo
Upload simples
Ao fazer upload de um objeto para um bucket com versionamento habilitado, o OSS gera um ID de versão exclusivo para o objeto e o inclui no cabeçalho de resposta x-oss-version-id. Ao fazer upload de um objeto para um bucket com versionamento suspenso, o ID de versão gerado para o objeto é null. Se você fizer upload de um objeto com o mesmo nome de um objeto existente em um bucket com versionamento suspenso, o objeto existente será sobrescrito. Dessa forma, cada objeto possui apenas uma única versão cujo ID de versão é null.
O código de exemplo a seguir mostra como fazer upload de um objeto para um bucket com versionamento habilitado usando upload simples:
package main
import (
"log"
"net/http"
"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 the bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
var retHeader http.Header
// Upload the string. Use oss.GetResponseHeader to retrieve the returned header.
// 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), oss.GetResponseHeader(&retHeader))
if err != nil {
log.Fatalf("Failed to put object '%s': %v", objectName, err)
}
// Display the value of the x-oss-version-id header.
versionId := oss.GetVersionId(retHeader)
log.Printf("x-oss-version-id: %s", versionId)
}
Upload por append
Em um bucket com versionamento habilitado, a operação AppendObject só pode ser executada em um objeto cuja versão atual seja do tipo appendable.
Ao executar a operação AppendObject na versão atual de um objeto appendable, o OSS não gera uma versão anterior para o objeto.
Ao executar a operação PutObject ou DeleteObject na versão atual de um objeto appendable, o OSS salva o objeto appendable como uma versão anterior que não aceita mais appends.
Não é possível executar a operação AppendObject na versão atual de um objeto não-appendable, como um objeto normal ou um delete marker.
O código de exemplo a seguir mostra como fazer upload de um objeto para um bucket com versionamento habilitado usando upload por append:
package main
import (
"log"
"net/http"
"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 the bucket.
bucketName := "yourBucketName"
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// The position for the first append upload is 0, and the position for the next append upload is included in the response. The position from which the next append operation starts is the current length of the object.
// Specify the full path of the object. Do not include the bucket name in the full path.
objectName := "yourObjectName"
var retHeader http.Header
var nextPos int64 = 0
// Perform the first append operation.
nextPos, err = bucket.AppendObject(objectName, strings.NewReader("YourObjectAppendValue1"), nextPos, oss.GetResponseHeader(&retHeader))
if err != nil {
log.Fatalf("Failed to append object '%s': %v", objectName, err)
}
log.Printf("x-oss-version-id: %s", retHeader.Get("x-oss-version-id"))
// Perform the second append operation.
nextPos, err = bucket.AppendObject(objectName, strings.NewReader("YourObjectAppendValue2"), nextPos, oss.GetResponseHeader(&retHeader))
if err != nil {
log.Fatalf("Failed to append object '%s': %v", objectName, err)
}
log.Printf("x-oss-version-id: %s", oss.GetVersionId(retHeader))
// You can append content to an object multiple times.
}
Upload multipart
Ao chamar a operação CompleteMultipartUpload para concluir a tarefa de upload multipart de um objeto em um bucket com versionamento habilitado, o OSS gera um ID de versão exclusivo para o objeto e o retorna como valor do cabeçalho x-oss-version-id na resposta.
O código de exemplo a seguir mostra como fazer upload de um objeto para um bucket com versionamento habilitado usando upload multipart:
package main
import (
"fmt"
"net/http"
"os"
"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 {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 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 {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucketName := "examplebucket"
// Specify the full path of the object. Do not include the bucket name in the full path.
objectName := "exampleobject.txt"
// Specify the full path of the local file that you want to upload. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs.
locaFilename := "D:\\localpath\\examplefile.txt"
// Use oss.GetResponseHeader to obtain the returned header.
var retHeader http.Header
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
chunks, err := oss.SplitFileByPartNum(locaFilename, 3)
fd, err := os.Open(locaFilename)
defer fd.Close()
// Step 1: Initiate a multipart upload task.
imur, err := bucket.InitiateMultipartUpload(objectName)
// Step 2: Upload the parts.
var parts []oss.UploadPart
for _, chunk := range chunks {
fd.Seek(chunk.Offset, os.SEEK_SET)
// Call the UploadPart method to upload each part.
part, err := bucket.UploadPart(imur, fd, chunk.Size, chunk.Number)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
parts = append(parts, part)
}
// Step 3: Complete the multipart upload task.
cmur, err := bucket.CompleteMultipartUpload(imur, parts, oss.GetResponseHeader(&retHeader))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println("cmur:", cmur)
// Display the value of the x-oss-version-id header.
fmt.Println("x-oss-version-id:", oss.GetVersionId(retHeader))
}
Referências
Para mais informações sobre a operação de API para upload simples, consulte PutObject.
Para mais detalhes sobre a operação de API para upload por append, consulte AppendObject.
Para informações sobre a operação de API usada para concluir uma tarefa de upload multipart, consulte CompleteMultipartUpload.