Java için OSS SDK, nesnelerin yüklenmesi, indirilmesi ve kopyalanması sırasında veri bütünlüğünü sağlamak amacıyla MD5 ve CRC-64 doğrulamasını kullanır.
Notlar
Bu konuda China (Hangzhou) bölgesinin genel uç noktası kullanılmıştır. OSS ile aynı bölgedeki diğer Alibaba Cloud hizmetlerinden OSS'ye erişmek için dahili bir uç nokta kullanın. OSS bölgeleri ve uç noktaları hakkında daha fazla bilgi için bkz. Bölgeler ve uç noktalar.
Bu konuda erişim kimlik bilgileri ortam değişkenlerinden alınır. Erişim kimlik bilgilerinin nasıl yapılandırılacağı hakkında daha fazla bilgi için bkz. Erişim kimlik bilgilerini yapılandırma.
Bu konu, bir OSS uç noktası kullanarak bir OSSClient örneğinin nasıl oluşturulacağını gösterir. Özel etki alanı kullanma veya Security Token Service (STS) kimlik bilgileriyle kimlik doğrulama gibi alternatif yapılandırmalar için bkz. İstemci yapılandırma (Go SDK V1).
MD5 doğrulama
Bir dosya yüklerken veri bütünlüğünü ve doğruluğunu sağlamak amacıyla Content-MD5 üstbilgisini belirtebilirsiniz. OSS, aldığı verilerin MD5 hash değerini hesaplar. Hesaplanan hash değeri sizin sağladığınız değerle eşleşmezse OSS bir InvalidDigest özel durumu döndürür. Bir InvalidDigest özel durumu oluşursa dosyanın iletim sırasında değiştirilip değiştirilmediğini veya bozulup bozulmadığını kontrol edin ve dosyayı yeniden yükleyin.
putObject, getObject, appendObject, postObject ve uploadPart işlemleri MD5 doğrulamayı destekler.
Aşağıdaki kod, bir dosya yükleme işlemi sırasında MD5 doğrulamanın nasıl yapılacağını gösterir.
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)
}
CRC-64 doğrulama
CRC-64 doğrulama hakkında notlar:
putObject, getObject, appendObject ve uploadPart işlemleri CRC-64 doğrulamayı destekler.
Dosya yükleme, indirme ve kopyalama işlemleri için CRC veri doğrulama varsayılan olarak etkindir. İstemci tarafından hesaplanan CRC değeri sunucudan döndürülen değerle eşleşmezse bir hata döndürülür.
Aralık indirmeleri CRC-64 doğrulamayı desteklemez.
CRC-64 doğrulamanın etkinleştirilmesi belirli miktarda CPU kaynağı tüketir ve yükleme ile indirme hızlarını etkiler.
Aşağıdaki kod, bir nesneye veri eklerken CRC-64 veri bütünlüğü doğrulamasının nasıl yapılacağını gösterir.
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.")
}