La función de instantáneas de documentos permite generar una instantánea de una página específica de un documento en la nube, como un archivo de Word, Excel, PPT o PDF, sin necesidad de descargar el archivo. Esta función admite diversos escenarios, como la inserción en páginas web y la copia de seguridad de datos.
Escenarios
Copia de seguridad y recuperación de datos: puede crear periódicamente instantáneas de los documentos almacenados en sus buckets de Object Storage Service (OSS) para realizar copias de seguridad.
Extracción de información clave: utilice las instantáneas de documentos para capturar una página específica y extraer rápidamente la información más relevante.
Cómo utilizar esta función
Requisitos previos
En Object Storage Service (OSS), debe create a bucket, upload the document to be processed al bucket y attach an Intelligent Media Management (IMM) project al bucket. El proyecto de IMM debe encontrarse en la misma región que el bucket.
Instantáneas de documentos
Utilice un SDK para llamar a la API de instantáneas de documentos y procesarlas.
Java
package com.aliyun.oss.demo;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import java.net.URL;
import java.util.Date;
public class Demo {
public static void main(String[] args) throws Throwable {
// The China (Hangzhou) region is used as an example. Set the Endpoint to the actual region.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. If the document is not in the root directory of the bucket, you must include the full path, for example, exampledir/demo.docx.
String objectName = "demo.docx";
// Specify the region where the bucket is located. The China (Hangzhou) region is used as an example. Set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer needed, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Build the document snapshot processing instruction to get a snapshot of the second page of the document.
String style = "doc/snapshot,target_jpg,source_docx,page_2";
// Set the expiration time of the signed URL to 3,600 seconds.
Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
req.setExpiration(expiration);
req.setProcess(style);
URL signedUrl = ossClient.generatePresignedUrl(req);
System.out.println(signedUrl);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Python
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the bucket name.
bucket = 'examplebucket'
# Specify the Endpoint for the region where the bucket is located. The China (Hangzhou) region is used as an example.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the general-purpose Alibaba Cloud region ID.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, bucket, region=region)
# Specify the source document name. If the document is not in the root directory of the bucket, you must include the full path, for example, exampledir/demo.docx.
key = 'demo.docx'
# Specify the expiration time in seconds.
expire_time = 3600
# Build the document snapshot processing instruction to get a snapshot of the second page of the document.
process = 'doc/snapshot,target_jpg,source_docx,page_2 '
# Generate a signed URL with image processing parameters.
url = bucket.sign_url('GET', key, expire_time, params={'x-oss-process': process}, slash_safe=True)
# Print the signed URL.
print(url)
Go
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
// Obtain access credentials from environment variables. Before running this 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 {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of the bucket. The China (Hangzhou) region is used as an example. Set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. Set other regions as needed.
// Set yourRegion to the region where the bucket is located. The China (Hangzhou) region is used as an example. Set the region to cn-hangzhou. Set other regions 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 {
HandleError(err)
}
// Specify the name of the bucket where the document is stored, for example, examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// Specify the document name. If the document is not in the root directory of the bucket, you must include the full path, for example, exampledir/demo.docx.
ossObjectName := "demo.docx"
// Generate a signed URL and set the expiration time to 3,600s. (The maximum validity period is 32,400 seconds.)
signedURL, err := bucket.SignURL(ossObjectName, oss.HTTPGet, 3600, oss.Process("doc/snapshot,target_jpg,source_docx,page_2"))
if err != nil {
HandleError(err)
} else {
fmt.Println(signedURL)
}
}
Node.js
const OSS = require("ali-oss");
// Define a function to generate a signed URL.
async function generateSignatureUrl(fileName) {
// Get the signed URL.
const client = await new OSS({
// Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
bucket: 'examplebucket',
// Set yourregion to the region where the bucket is located. The China (Hangzhou) region is used as an example. Set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Set secure to true to use HTTPS and prevent the browser from blocking the generated download link.
secure: true,
authorizationV4: true
});
return await client.signatureUrlV4('GET', 3600, {
headers: {}, // Set the request headers based on the actual request that you send.
queries: {
"x-oss-process": "doc/snapshot,target_jpg,source_docx,page_1" // Build the document snapshot processing instruction to get a snapshot of the first page of the document.
}
}, fileName);
}
// Call the function and pass the file name.
generateSignatureUrl('yourFileName').then(url => {
console.log('Generated Signature URL:', url);
}).catch(err => {
console.error('Error generating signature URL:', err);
});
PHP
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
// Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the Endpoint for the region where the bucket is located. The China (Hangzhou) region is used as an example. Set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Set yourRegion to the region where the bucket is located. The China (Hangzhou) region is used as an example. Set the region to cn-hangzhou. Set other regions as needed.
$region = "yourRegion";
// Specify the bucket name, for example, examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object, for example, exampledir/demo.docx. The full path of the object cannot contain the bucket name.
$object = "exampledir/demo.docx";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> $region
);
$ossClient = new OssClient($config);
// Generate a signed URL with image processing parameters. The URL is valid for 3,600 seconds and can be accessed directly in a browser.
$timeout = 3600;
$options = array(
// Build the document snapshot processing instruction to get a snapshot of the first page of the document.
OssClient::OSS_PROCESS => "doc/snapshot,target_jpg,source_docx,page_1");
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("Signed URL: \n" . $signedUrl);
A continuación se muestra un ejemplo de una URL firmada generada:
https://examplebucket.oss-cn-hangzhou.aliyuncs.com/demo.docx?x-oss-process=doc%2Fsnapshot%2Ctarget_jpg%2Csource_docx%2Cpage_1&x-oss-date=20250225T023122Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI********************%2F20250225%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=c6620caa4dc160e5a70ee96b5bae08464edf7a41bb6d47432eda65474f68f26a
Copie la URL generada y péguela en la barra de direcciones de su navegador para consultar la instantánea del documento especificada.
Parámetros
Acción: doc/snapshot
La siguiente tabla describe los parámetros.
|
Parámetro |
Tipo |
Obligatorio |
Descripción |
|
target |
string |
No |
Formato de destino de la imagen. Valores válidos:
|
|
source |
string |
No |
Formato de archivo del documento de origen. De forma predeterminada, se utiliza la extensión del nombre del objeto. Valores válidos:
Nota
Si no especifica este parámetro y el objeto no tiene extensión de archivo, se devuelve un error. |
|
page |
int |
No |
Número de página del documento. El valor predeterminado es 1, que corresponde a la primera página. El valor máximo es 2000. |
Operaciones de API relacionadas
Las operaciones anteriores se implementan mediante llamadas a la API. Si su programa requiere un alto nivel de personalización, puede enviar directamente solicitudes de la API REST. Al enviar solicitudes de la API REST, debe escribir manualmente el código para calcular la firma. Para obtener más información sobre cómo calcular el encabezado de solicitud común Authorization, consulte Signature Version 4 (recommended).
Obtener una instantánea de la primera página de example.docx
Método de procesamiento
Procesamiento predeterminado
Ejemplo
// Get a snapshot of the first page of example.docx.
GET /exmaple.docx?x-oss-process=doc/snapshot HTTP/1.1
Host: doc-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
Obtener una instantánea JPG de la segunda página del documento de Word example
Método de procesamiento
target: jpg
source: docx
page: 2
Ejemplo
// Get a JPG snapshot of the second page of the Word document example.
GET /exmaple?x-oss-process=doc/snapshot,target_jpg,source_docx,page_2 HTTP/1.1
Host: doc-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
Permisos
Una cuenta de Alibaba Cloud tiene todos los permisos de forma predeterminada. Un usuario o rol de Resource Access Management (RAM) bajo una cuenta de Alibaba Cloud no tiene ningún permiso por defecto. La cuenta de Alibaba Cloud o un administrador deben otorgar permisos mediante una RAM policy o un bucket policy.
|
API |
Action |
Descripción |
|
GetObject |
|
Descarga un objeto. |
|
|
Este permiso es obligatorio si, al descargar un objeto, se especifica la versión del objeto mediante versionId. |
|
|
|
Este permiso es obligatorio si, al descargar un objeto, los metadatos del objeto contienen X-Oss-Server-Side-Encryption: KMS. |
|
API |
Action |
Descripción |
|
Ninguna |
|
Permite utilizar las capacidades de procesamiento de datos de IMM en OSS. |
|
API |
Action |
Descripción |
|
CreateOfficeConversionTask |
|
Permiso para utilizar IMM en la conversión de documentos o la generación de instantáneas. |
Facturación
Las instantáneas de documentos generan cargos por los siguientes conceptos facturables. Para obtener más información sobre los precios de estos conceptos, consulte Precios de OSS y Billable items:
|
API |
Concepto facturable |
Descripción |
|
GetObject |
Solicitudes GET |
Se aplican tarifas por solicitud según el número de solicitudes exitosas. |
|
Tráfico de salida a través de Internet |
Si llama a la operación GetObject mediante un endpoint público, como oss-cn-hangzhou.aliyuncs.com, o un endpoint de aceleración, como oss-accelerate.aliyuncs.com, se aplican tarifas por tráfico de salida a través de Internet según el tamaño de los datos. |
|
|
Recuperación de objetos IA |
Si se recuperan objetos IA, se aplican tarifas por recuperación de datos IA según el tamaño de los datos IA recuperados. |
|
|
Recuperación de objetos Archive en un bucket con acceso en tiempo real habilitado |
Si recupera objetos Archive en un bucket con acceso en tiempo real habilitado, se aplican tarifas por recuperación de datos Archive según el tamaño de los objetos Archive recuperados. |
|
|
Tarifas por aceleración de transferencia |
Si habilita la aceleración de transferencia y utiliza un endpoint de aceleración para acceder a su bucket, se aplican tarifas por aceleración de transferencia según el tamaño de los datos. |
|
API |
Concepto facturable |
Descripción |
|
CreateOfficeConversionTask |
DocumentConvert |
Se aplican tarifas por solicitud según el número de solicitudes exitosas. |
Notas
Las instantáneas de documentos solo admiten procesamiento síncrono (el método x-oss-process).
Preguntas frecuentes
¿Cuál es el tamaño máximo de un documento de origen para una instantánea de documento?
El tamaño máximo de un documento de origen para una instantánea de documento es de 20 MB.