Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:Prevent objects from being overwritten by objects that have the same names (OSS SDK for Go 1.0)

Son Güncelleme:Oct 01, 2026

Varsayılan olarak, mevcut bir nesneyle aynı ada sahip bir nesne yüklediğinizde yüklenen nesne mevcut nesnenin üzerine yazar. Bu konu, nesneleri kopyalarken veya basit yükleme ya da çok parçalı yükleme yaparken aynı ada sahip nesnelerin mevcut nesnelerin üzerine yazılmasını önlemek için x-oss-forbid-overwrite istek üst bilgisinin nasıl yapılandırılacağını açıklar.

Notlar

  • Bu konuda Çin (Hangzhou) bölgesinin genel uç noktası kullanılır. OSS ile aynı bölgedeki diğer Alibaba Cloud hizmetlerinden OSS'ye erişmek için dahili 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 konuda bir OSS uç noktası kullanarak OSSClient örneği oluşturma işlemi gösterilir. Özel etki alanı kullanma veya Security Token Service (STS) kimlik bilgileriyle kimlik doğrulama gibi alternatif yapılandırmalar için bkz. Bir istemci yapılandırma (Go SDK V1).

Örnek kod

Aşağıdaki örnek kod, basit yükleme sırasında aynı ada sahip nesnelerin mevcut nesnelerin üzerine yazılmasını nasıl önleyeceğinizi gösterir:

package main

import (
	"log"
	"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 your bucket. 
	bucketName := "yourBucketName"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify whether to overwrite an existing object with the same name. 
        // By default, if you do not specify oss.ForbidOverWrite, an object that has the same name is overwritten. 
        // If you set oss.ForbidOverWrite to false, an object that has the same name is overwritten. 
        // If you set oss.ForbidOverWrite to true, an object that has the same name is not overwritten. If such an object exists, an error is reported. 
	forbidWrite := oss.ForbidOverWrite(true)

	// Upload the string. 
        // 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), forbidWrite)
	if err != nil {
		log.Fatalf("Failed to upload object '%s': %v", objectName, err)
	}

	log.Printf("Successfully uploaded object '%s' with value '%s'", objectName, objectValue)
}

Yaygın senaryolar

Nesne kopyalama görevinde üzerine yazmayı önleme

Aşağıdaki örnek kod, aynı ada sahip yeni kopyalanan nesnelerin mevcut nesnelerin üzerine yazılmasını nasıl önleyeceğinizi gösterir:

package main

import (
	"log"

	"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 your bucket. 
	bucketName := "yourBucketName"
	// Specify the full path of the source object. Do not include the bucket name in the full path.
	objectName := "yourObjectName"
	// Specify the full path of the destination object. Do not include the bucket name in the full path.
	destObjectName := "yourDestObjectName"

	// Specify the name of the bucket.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Specify whether to overwrite an existing object with the same name. 
	// By default, if you do not specify oss.ForbidOverWrite, an object that has the same name is overwritten. 
	// If you set oss.ForbidOverWrite to false, an object that has the same name is overwritten. 
	// If you set oss.ForbidOverWrite to true, an object that has the same name is not overwritten. If such an object exists, an error is reported. 
	forbidWrite := oss.ForbidOverWrite(true)

	// Create a copy of the object within the bucket.
	_, err = bucket.CopyObject(objectName, destObjectName, forbidWrite)
	if err != nil {
		log.Fatalf("Failed to copy object from '%s' to '%s': %v", objectName, destObjectName, err)
	}

	log.Printf("Successfully copied object from '%s' to '%s'", objectName, destObjectName)
}

Çok parçalı yükleme görevinde üzerine yazmayı önleme

Aşağıdaki örnek kod, çok parçalı yükleme kullanarak bir nesne yüklerken aynı ada sahip bir nesnenin mevcut nesnenin üzerine yazılmasını nasıl önleyeceğinizi gösterir:

package main

import (
	"log"
	"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 {
		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"
	// Specify the full path of the object. Do not include the bucket name in the full path. 
	objectName := "yourObjectName"
	// Specify the full path of the local file. 
	localFilename := "yourLocalFilename"

	// Specify the name of the bucket.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
	}

	// Split the object into multiple chunks.
	chunks, err := oss.SplitFileByPartNum(localFilename, 3)
	if err != nil {
		log.Fatalf("Failed to split file: %v", err)
	}

	// Open the local file.
	fd, err := os.Open(localFilename)
	if err != nil {
		log.Fatalf("Failed to open local file '%s': %v", localFilename, err)
	}
	defer fd.Close()

	// Specify whether to overwrite an existing object with the same name. 
	// By default, if you do not specify oss.ForbidOverWrite, an object that has the same name is overwritten. 
	// If you set oss.ForbidOverWrite to false, an object that has the same name is overwritten. 
	// If you set oss.ForbidOverWrite to true, an object that has the same name is not overwritten. If such an object exists, an error is reported. 
	forbidWrite := oss.ForbidOverWrite(true)

	// Step 1: Initiate a multipart upload task. 
	imur, err := bucket.InitiateMultipartUpload(objectName, forbidWrite)
	if err != nil {
		log.Fatalf("Failed to initiate multipart upload for '%s': %v", objectName, err)
	}

	// 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 {
			log.Fatalf("Failed to upload part %d of '%s': %v", chunk.Number, objectName, err)
		}
		parts = append(parts, part)
	}

	// Step 3: Complete the multipart upload task. Disable overwrites between objects that have the same names. 
	cmur, err := bucket.CompleteMultipartUpload(imur, parts, forbidWrite)
	if err != nil {
		log.Fatalf("Failed to complete multipart upload for '%s': %v", objectName, err)
	}

	log.Printf("Multipart upload completed successfully for '%s'. cmur: %v", objectName, cmur)
}

Başvurular

  • Basit yükleme yapmak için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. PutObject.

  • Bir nesneyi kopyalamak için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. CopyObject.

  • Çok parçalı yükleme yapmak için çağırabileceğiniz API işlemleri hakkında daha fazla bilgi için bkz. InitiateMultipartUpload ve CompleteMultipartUpload.