Todos los productos
Search
Centro de documentos

Object Storage Service:Comprobar si un archivo existe (Go SDK V1)

Última actualización: Sep 24, 2026

Este tema describe cómo comprobar si un archivo existe.

Notas

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para determinar si un objeto existe, necesita el permiso oss:GetObject. Para obtener más información, consulte Grant a custom policy.

Código de ejemplo

A continuación se muestra un código de ejemplo para comprobar si un archivo existe.

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 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 the bucket. For example, for a bucket in the China (Hangzhou) region, set the value to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the value as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the value to cn-hangzhou. For other regions, set the value as needed.
	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 the bucket.
	bucketName := "yourBucketName" // Replace with the actual bucket name.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}

	// Check whether the file exists.
	// Set yourObjectName to the full path of the object. Do not include the bucket name.
	objectName := "yourObjectName" // Replace with the actual object path.
	isExist, err := bucket.IsObjectExist(objectName)
	if err != nil {
		log.Fatalf("Failed to check if object exists: %v", err)
	}
	log.Printf("Exist: %t\n", isExist)
}

Referencias

  • Para obtener más información sobre la operación de API que comprueba si un archivo existe, consulte IsObjectExist.