Puede llamar a la operación AppendObject para agregar contenido a objetos anexables existentes.
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 en la misma región que OSS, use 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).
Si el objeto al que desea agregar contenido no existe, la operación AppendObject crea un objeto anexable.
-
Si el objeto al que desea agregar contenido ya existe:
Si el objeto es anexable y la posición especificada para iniciar la operación coincide con el tamaño actual del objeto, los datos se agregan al final del objeto.
Si el objeto es anexable pero la posición especificada para iniciar la operación no coincide con el tamaño actual del objeto, se devuelve el error PositionNotEqualToLength.
Si el objeto no es anexable, se devuelve el error ObjectNotAppendable.
Permisos
De forma predeterminada, una cuenta de Alibaba Cloud tiene permisos completos. Los usuarios o roles de RAM bajo una cuenta de Alibaba Cloud no tienen ningún permiso de manera predeterminada. La cuenta de Alibaba Cloud o el administrador de la cuenta debe otorgar los permisos de operación mediante RAM policies o Bucket Policy.
|
API |
Action |
Descripción |
|
AppendObject |
|
Llame a esta operación para cargar un objeto y agregarlo a uno existente. |
|
|
Este permiso es obligatorio cuando se cargue un objeto por anexión y se especifiquen etiquetas mediante x-oss-tagging. |
Código de ejemplo
A continuación se muestra el código para ejecutar una carga por anexión:
package main
import (
"log"
"strings"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of the bucket. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
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 bucket name, for example, examplebucket.
bucketName := "examplebucket" // Replace with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Specify the full path of the object. Do not include the bucket name. For example, appendobject.txt.
objectName := "appendobject.txt"
var nextPos int64 = 0
// Specify the expiration time.
expires := time.Date(2025, time.December, 10, 23, 0, 0, 0, time.UTC)
options := []oss.Option{
oss.Expires(expires),
}
// The position for the first append upload is 0. The return value is the position for the next append upload.
appendValue1 := "YourObjectAppendValue1"
nextPos, err = bucket.AppendObject(objectName, strings.NewReader(appendValue1), nextPos, options...)
if err != nil {
log.Fatalf("Failed to append first value: %v", err)
}
// Perform the second append upload.
appendValue2 := "YourObjectAppendValue2"
nextPos, err = bucket.AppendObject(objectName, strings.NewReader(appendValue2), nextPos)
if err != nil {
log.Fatalf("Failed to append second value: %v", err)
}
log.Println("Append uploads completed successfully.")
}
Preguntas frecuentes
Referencias
Para consultar el código de ejemplo completo de cargas por anexión, vea el ejemplo en GitHub.
Para obtener más información sobre la operación de API AppendObject, consulte AppendObject.