O recurso de snapshot de documentos gera uma imagem de uma página específica de um arquivo (como Word, Excel, PPT ou PDF) diretamente na nuvem, sem necessidade de download. Essa funcionalidade atende a diversos cenários, como incorporação em páginas web e backup de dados.
Cenários
Backup e recuperação de dados: Crie snapshots periódicos dos documentos armazenados nos buckets do Object Storage Service (OSS) para garantir a segurança das informações.
Extração de informações essenciais: Capture páginas específicas com snapshots para extrair dados importantes de forma ágil.
Como usar este recurso
Pré-requisitos
No Object Storage Service (OSS), você deve criar um bucket, fazer upload do documento a ser processado para o bucket e anexar um projeto do Intelligent Media Management (IMM) ao bucket. O projeto IMM deve estar na mesma região do bucket.
Snapshots de documentos
Use um SDK para chamar a API de snapshot de documentos e processá-los.
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);
Veja abaixo um exemplo de URL assinada gerada:
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 a URL gerada e cole-a na barra de endereços do navegador para visualizar o snapshot do documento especificado.
Parâmetros
Ação: doc/snapshot
A tabela a seguir descreve os parâmetros.
|
Parâmetro |
Tipo |
Obrigatório |
Descrição |
|
target |
string |
Não |
Formato de destino da imagem. Valores válidos:
|
|
source |
string |
Não |
Formato de arquivo do documento de origem. Por padrão, o sistema usa a extensão do nome do objeto. Valores válidos:
Nota
Se você não especificar este parâmetro e o objeto não tiver extensão de arquivo, o sistema retornará um erro. |
|
page |
int |
Não |
Número da página do documento. O valor padrão é 1 (primeira página). O valor máximo é 2000. |
Operações de API relacionadas
As operações anteriores usam chamadas de API. Se o seu programa exigir alta personalização, envie solicitações REST API diretamente. Nesse caso, escreva manualmente o código para calcular a assinatura. Para mais detalhes sobre como calcular o cabeçalho de solicitação comum Authorization, consulte Signature Version 4 (recommended).
Obter um snapshot da primeira página de example.docx
Método de processamento
Processamento padrão
Exemplo
// 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
Obter um snapshot JPG da segunda página do documento Word example
Método de processamento
target: jpg
source: docx
page: 2
Exemplo
// 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
Permissões
Uma conta Alibaba Cloud tem permissões totais por padrão. Usuários ou funções do Resource Access Management (RAM) vinculados a essa conta não têm permissões configuradas inicialmente. A conta Alibaba Cloud ou um administrador deve conceder as permissões necessárias usando uma RAM policy ou uma bucket policy.
|
API |
Ação |
Descrição |
|
GetObject |
|
Baixa um objeto. |
|
|
Necessária ao baixar um objeto com versão especificada por versionId. |
|
|
|
Exigida quando os metadados do objeto baixado contêm X-Oss-Server-Side-Encryption: KMS. |
|
API |
Ação |
Descrição |
|
Nenhuma |
|
Permite usar os recursos de processamento de dados do IMM no OSS. |
|
API |
Ação |
Descrição |
|
CreateOfficeConversionTask |
|
Autoriza o uso do IMM para conversão de documentos ou geração de snapshots. |
Faturamento
Os snapshots de documentos incorrem nos seguintes itens faturáveis. Para mais informações sobre os preços desses itens, consulte Preços do OSS e Billable items:
|
API |
Item faturável |
Descrição |
|
GetObject |
Solicitações GET |
Cobrança de taxas de solicitação com base na quantidade de requisições bem-sucedidas. |
|
Tráfego de saída pela Internet |
Chamadas à operação GetObject via endpoint público (como oss-cn-hangzhou.aliyuncs.com) ou endpoint de aceleração (como oss-accelerate.aliyuncs.com) geram cobrança de tráfego de saída baseada no volume de dados. |
|
|
Recuperação de objetos IA |
A recuperação de objetos de Acesso Infrequente (IA) gera taxas proporcionais ao tamanho dos dados recuperados. |
|
|
Recuperação de objetos Archive em bucket com acesso em tempo real ativado |
A recuperação de objetos Archive em buckets com acesso em tempo real habilitado gera taxa de recuperação baseada no tamanho dos arquivos acessados. |
|
|
Taxas de aceleração de transferência |
O uso de endpoint de aceleração com a aceleração de transferência ativa gera taxas correspondentes ao volume de dados transferido. |
|
API |
Item faturável |
Descrição |
|
CreateOfficeConversionTask |
DocumentConvert |
Cobrança de taxas de solicitação baseada no número de requisições concluídas com sucesso. |
Observações
Snapshots de documentos aceitam apenas processamento síncrono (método x-oss-process).
Perguntas frequentes
Qual é o tamanho máximo do documento de origem para um snapshot?
O tamanho máximo do documento de origem para geração de snapshots é de 20 MB.