O OSS SDK for Java usa verificação MD5 e CRC-64 para garantir a integridade dos dados durante uploads, downloads e cópias de objetos.
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 mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste exemplo, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configure credenciais de acesso, consulte Configure credenciais de acesso.
Este tópico demonstra como crie uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configure um cliente (Go SDK V1).
Validação MD5
Ao fazer upload de um arquivo, especifique o cabeçalho Content-MD5 para garantir a integridade e a precisão dos dados. O OSS calcula o hash MD5 dos dados recebidos. Se o hash calculado não corresponder ao hash fornecido, o OSS retorna uma exceção InvalidDigest. Caso ocorra essa exceção, verifique se o arquivo foi alterado ou corrompido durante a transmissão e refaça o upload.
As operações putObject, getObject, appendObject, postObject e uploadPart suportam validação MD5.
O código a seguir mostra um exemplo de validação MD5 durante o upload de um arquivo.
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)
}
Validação CRC-64
Observações sobre a validação CRC-64:
As operações putObject, getObject, appendObject e uploadPart suportam validação CRC-64.
A validação de dados CRC é ativada por padrão para uploads, downloads e cópias de arquivos. Se o valor CRC calculado pelo cliente não corresponder ao valor retornado pelo servidor, o sistema retornará um erro.
Downloads por intervalo (range downloads) não suportam validação CRC-64.
A ativação da validação CRC-64 consome recursos de CPU e afeta as velocidades de upload e download.
O código a seguir mostra um exemplo de validação de integridade de dados CRC-64 ao anexar dados a um 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.")
}