En este tema se describe cómo cargar objetos en un bucket con control de versiones habilitado.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si necesita acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).
Para cargar un objeto, debe contar con el permiso
oss:PutObject. Para obtener más información, consulte Grant a custom policy.
Código de ejemplo
Carga simple
Si carga un objeto en un bucket con control de versiones habilitado, OSS genera un identificador de versión único para dicho objeto e incluye ese identificador en el encabezado de respuesta x-oss-version-id. Si lo carga en un bucket con control de versiones suspendido, el identificador generado es null. Además, si carga un objeto con el mismo nombre que uno ya existente en un bucket con control de versiones suspendido, el objeto existente se sobrescribe. De esta manera, cada objeto conserva únicamente una versión cuyo identificador es null.
A continuación se muestra un ejemplo de código para cargar un objeto en un bucket con control de versiones habilitado mediante una carga simple:
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)
}
Carga por anexión
En un bucket con control de versiones habilitado, la operación AppendObject solo se puede ejecutar en un objeto cuya versión actual sea anexable.
Cuando ejecuta la operación AppendObject en la versión actual de un objeto anexable, OSS no genera una versión anterior para dicho objeto.
Cuando ejecuta la operación PutObject o DeleteObject en la versión actual de un objeto anexable, OSS guarda ese objeto como una versión anterior a la que ya no se le pueden agregar datos.
La operación AppendObject no se puede ejecutar en la versión actual de un objeto no anexable, como un objeto normal o un marcador de eliminación.
El siguiente ejemplo de código muestra cómo cargar un objeto en un bucket con control de versiones habilitado mediante una carga por anexión:
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.
}
Carga multiparte
Si llama a la operación CompleteMultipartUpload para finalizar la tarea de carga multiparte de un objeto en un bucket con control de versiones habilitado, OSS genera un identificador de versión único para dicho objeto. Este identificador se devuelve como valor del encabezado x-oss-version-id en la respuesta.
El siguiente ejemplo de código muestra cómo cargar un objeto en un bucket con control de versiones habilitado mediante una carga multiparte:
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))
}
Referencias
Para obtener más información sobre la operación de API que permite ejecutar una carga simple, consulte PutObject.
Para conocer más detalles sobre la operación de API que permite ejecutar una carga por anexión, consulte AppendObject.
Si desea más información sobre la operación de API que permite finalizar una tarea de carga multiparte, consulte CompleteMultipartUpload.