OSS SDK for Java utiliza la verificación MD5 y CRC-64 para garantizar la integridad de los datos durante las operaciones de carga, descarga y copia de objetos.
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, 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).
Validación MD5
Cuando cargue un archivo, especifique el encabezado Content-MD5 para garantizar la integridad y exactitud de los datos. OSS calcula el hash MD5 de los datos que recibe. Si el hash calculado no coincide con el hash proporcionado, OSS devuelve una excepción InvalidDigest. Si ocurre una excepción InvalidDigest, compruebe si el archivo se modificó o se dañó durante la transmisión y vuelva a cargarlo.
Las operaciones putObject, getObject, appendObject, postObject y uploadPart admiten la validación MD5.
A continuación se muestra un ejemplo de código para aplicar la validación MD5 durante la carga de un archivo.
package main
import (
"crypto/md5"
"encoding/base64"
"log"
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
// Calculate the MD5 checksum for the given content.
func calculateMD5(content string) string {
h := md5.New()
h.Write([]byte(content))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func main() {
// Load OSS access credentials from environment variables.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Replace with your actual bucket name.
bucketName := "yourBucketName"
// Create an OSS client.
// Set yourEndpoint to the Endpoint of your bucket. For example, for the China (Hangzhou) region, set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where your bucket is located. For example, for the China (Hangzhou) region, set it to cn-hangzhou. For other regions, use the actual region ID.
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)
}
// Get the specified bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket %s: %v", bucketName, err)
}
// The content to upload.
content := "yourObjectValue" // Replace with the actual content to upload.
objectName := "yourObjectName" // Replace with the actual object name.
// Calculate the MD5 checksum of the content.
contentMD5 := calculateMD5(content)
// Upload the file to OSS.
err = bucket.PutObject(objectName, strings.NewReader(content), oss.ContentMD5(contentMD5))
if err != nil {
log.Fatalf("Failed to upload object %s: %v", objectName, err)
}
log.Printf("Object '%s' uploaded successfully.", objectName)
}
Validación CRC-64
Notas sobre la validación CRC-64:
Las operaciones putObject, getObject, appendObject y uploadPart admiten la validación CRC-64.
La validación de datos CRC está habilitada de forma predeterminada para las operaciones de carga, descarga y copia de archivos. Si el valor CRC calculado por el cliente no coincide con el valor que devuelve el servidor, se genera un error.
Las descargas por rangos no admiten la validación CRC-64.
Habilitar la validación CRC-64 consume recursos de CPU y afecta la velocidad de carga y descarga.
A continuación se muestra un ejemplo de código para aplicar la validación de integridad de datos CRC-64 al agregar datos a un objeto.
package main
import (
"log"
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before running this code, make sure 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 your bucket. For example, for the China (Hangzhou) region, set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where your bucket is located. For example, for the China (Hangzhou) region, set it to cn-hangzhou. For other regions, use the actual region ID.
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)
}
// Set yourBucketName to the name of your bucket.
bucketName := "yourBucketName" // Replace with your actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket %s: %v", bucketName, err)
}
// Define the name of the object to which data will be appended.
objectName := "yourObjectName" // Replace with the actual object name.
// The position for the first append operation is 0. The return value indicates the position for the next append operation. Subsequent append positions are the length of the file before the append.
request := &oss.AppendObjectRequest{
ObjectKey: objectName,
Reader: strings.NewReader("YourObjectAppendValue1"),
Position: 0,
}
// For the first append operation, initialize the CRC value to 0.
options := []oss.Option{oss.InitCRC(0)}
result, err := bucket.DoAppendObject(request, options)
if err != nil {
log.Fatalf("Failed to append object %s for the first time: %v", objectName, err)
}
log.Printf("First append successful. Next position: %d", result.NextPosition)
// The position for the second append operation starts from the length returned by the first operation.
request = &oss.AppendObjectRequest{
ObjectKey: objectName,
Reader: strings.NewReader("YourObjectAppendValue2"),
Position: result.NextPosition,
}
// The initial CRC value for the second append operation is the return value from the first operation.
options = []oss.Option{oss.InitCRC(result.CRC)}
result, err = bucket.DoAppendObject(request, options)
if err != nil {
log.Fatalf("Failed to append object %s for the second time: %v", objectName, err)
}
log.Printf("Second append successful. Next position: %d", result.NextPosition)
// You can perform multiple AppendObject operations.
log.Printf("All appends completed successfully.")
}