Tüm Ürünler
Search
Belge Merkezi

Object Storage Service:Download objects as files (OSS SDK for Go 1.0)

Son Güncelleme:Oct 01, 2026

Bu konu, bir paketten bilgisayarınıza nasıl nesne indireceğinizi açıklar.

Kullanım notları

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

  • Bir nesneyi yerel dosya olarak indirmek için oss:GetObject iznine sahip olmanız gerekir. Daha fazla bilgi için bkz. Özel ilke atama.

Örnekler

Aşağıdaki örnek kod, examplebucket adlı bir paketin exampledir dizinindeki exampleobject.txt nesnesini D:\localpath konumuna indirme işlemini gösterir. Nesne indirildikten sonra yerel dosyanın adı examplefile.txt olur.

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 the bucket. Example: examplebucket. 
    bucketName := "examplebucket" // Replace examplebucket with the actual bucket name.
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        log.Fatalf("Failed to get bucket: %v", err)
    }

    // Download the object to the specified local path. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path. 
    // If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
    // Specify the full path of the object that you want to download from the bucket. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file in which you want to store the downloaded object. Example: D:\\localpath\\examplefile.txt. Do not include the bucket name in the full path. 
    objectName := "exampledir/exampleobject.txt"
    localFilePath := "D:\\localpath\\examplefile.txt"
    err = bucket.GetObjectToFile(objectName, localFilePath)
    if err != nil {
        log.Fatalf("Failed to download file: %v", err)
    }

    log.Println("File downloaded successfully.")
}

Yaygın senaryolar

Koşullu indirme

Bir paketten tek bir nesne indirirken nesnenin son değiştirilme zamanına veya ETag değerine göre koşullar belirtebilirsiniz. Nesne yalnızca bu koşullar karşılandığında indirilir. Aksi takdirde hata döndürülür ve indirme işlemi tetiklenmez. Bu yaklaşım gereksiz ağ aktarımını ve kaynak tüketimini azaltarak indirme verimliliğini artırır.

Aşağıdaki tabloda belirtilebilen mevcut koşullar açıklanmaktadır.

Not
  • If-Modified-Since ve If-Unmodified-Since birlikte kullanılabilir. If-Match ve If-None-Match de birlikte kullanılabilir.

  • ETag değerini almak için ossClient.getObjectMetadata yöntemini çağırın.


Koşul


Açıklama


Yöntem


IfModifiedSince


Belirtilen zaman, bir nesnenin son değiştirilme zamanından önceyse nesne indirilebilir. Aksi takdirde 304 Not Modified döndürülür.


oss.IfModifiedSince


IfUnmodifiedSince


Belirtilen zaman, bir nesnenin son değiştirilme zamanından sonra veya buna eşitse nesne indirilebilir. Aksi takdirde 412 Precondition Failed döndürülür.


oss.IfUnmodifiedSince


IfMatch


Belirtilen ETag değeri bir nesneninkiyle eşleşiyorsa nesne indirilebilir. Aksi takdirde 412 Precondition Failed döndürülür.


oss.IfMatch


IfNoneMatch


Belirtilen ETag değeri bir nesneninkiyle eşleşmiyorsa nesne indirilebilir. Aksi takdirde 304 Not Modified döndürülür.


oss.IfNoneMatch

Aşağıdaki örnek kod, koşullu indirme işleminin nasıl yapılacağını gösterir:

package main

import (
    "log"
    "time"
    
    "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" // Replace yourBucketName with the actual bucket name.
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        log.Fatalf("Failed to get bucket: %v", err)
    }

    // For example, an object was last modified at 18:43:02, November 21, 2023. If the specified time is earlier than the last modified time, the object meets the If-Modified-Since condition and the object is downloaded. 
    date := time.Date(2023, time.November, 21, 18, 43, 2, 0, time.UTC)

    // Specify the full path of the object. Do not include the bucket name in the full path. 
    objectName := "yourObjectName" // Replace yourObjectName with the actual object name.
    localFilePath := "LocalFile" // Specify the full path of the local file in which you want to store the downloaded object.

    // The object is not downloaded if it does not meet the specified conditions. 
    err = bucket.GetObjectToFile(objectName, localFilePath, oss.IfUnmodifiedSince(date))
    if err == nil {
        log.Fatal("Expected an error when the condition is not met, but got nil")
    }

    // The object is downloaded if it meets the specified conditions. 
    err = bucket.GetObjectToFile(objectName, localFilePath, oss.IfModifiedSince(date))
    if err != nil {
        log.Fatalf("Failed to download file: %v", err)
    }

    log.Println("File has been downloaded successfully.")
}

İndirme ilerlemesinin görüntülenmesi

Bir nesne indirirken indirme ilerlemesini gerçek zamanlı olarak görüntülemek için ilerleme çubuğunu kullanabilirsiniz. Bu sayede nesne indirmeyi uzun süre bekledikten sonra indirme görevinin takılıp takılmadığını kontrol edebilirsiniz.

Aşağıdaki örnek kod, examplebucket adlı bir paketten indirilen exampleobject.txt adlı bir nesnenin ilerlemesinin nasıl görüntüleneceğini gösterir:

package main

import (
	"log"
	"sync/atomic"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Specify the progress bar listener. 
type OssProgressListener struct {
	lastProgress int64
}

// Specify the function that is used to handle progress change events. 
func (listener *OssProgressListener) ProgressChanged(event *oss.ProgressEvent) {
	switch event.EventType {
	case oss.TransferStartedEvent:
		log.Printf("Transfer Started, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	case oss.TransferDataEvent:
		if event.TotalBytes != 0 {
			progress := int64(event.ConsumedBytes * 100 / event.TotalBytes)
			if progress > atomic.LoadInt64(&listener.lastProgress) {
				atomic.StoreInt64(&listener.lastProgress, progress)
				log.Printf("\rTransfer Data, ConsumedBytes: %d, TotalBytes %d, %d%%.",
					event.ConsumedBytes, event.TotalBytes, progress)
			}
		}
	case oss.TransferCompletedEvent:
		log.Printf("\nTransfer Completed, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	case oss.TransferFailedEvent:
		log.Printf("\nTransfer Failed, ConsumedBytes: %d, TotalBytes %d.\n",
			event.ConsumedBytes, event.TotalBytes)
	default:
	}
}

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("Error: %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("Error: %v", err)
	}

	// Specify the name of the bucket. 
	bucketName := "examplebucket"
	// Specify the full path of the object. Do not include the bucket name in the full path. 
	objectName := "exampleobject.txt"
	// Specify the full path of the local file in which you want to store the downloaded object. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path. 
	// If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
	localFile := "D:\\localpath\\examplefile.txt"

	// Query the name of the bucket. 
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	// Display the progress of the download task. 
	err = bucket.GetObjectToFile(objectName, localFile, oss.Progress(&OssProgressListener{}))
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	log.Println("Transfer Completed.")
}

İlgili kaynaklar

  • Bir nesneyi yerel dosya olarak indirmek için kullanılan tam örnek kodu görüntülemek üzere GitHub adresini ziyaret edin.

  • Bir nesneyi yerel dosya olarak indirmek için çağırabileceğiniz API işlemi hakkında daha fazla bilgi için bkz. GetObjectToFile.