Este tópico descreve como baixar um objeto de um bucket para o seu computador.
Observações de uso
Este tópico utiliza 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 mais sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).
Para baixar um objeto como arquivo local, você precisa da permissão
oss:GetObject. Para mais detalhes, consulte Conceder uma política personalizada.
Exemplos
O código de exemplo a seguir mostra como baixar o objeto exampleobject.txt do diretório exampledir em um bucket chamado examplebucket para D:\localpath. Após o download, o arquivo local recebe o nome examplefile.txt.
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.")
}
Cenários comuns
Referências
Para acessar o código de exemplo completo sobre como baixar um objeto como arquivo local, visite o GitHub.
Para mais informações sobre a operação de API usada para baixar um objeto como arquivo local, consulte GetObjectToFile.