Tous les produits
Search
Centre de documentation

Object Storage Service:Instantanés de documents

Dernière mise à jour :Aug 27, 2026

La fonctionnalité d'instantané de documents vous permet de générer un instantané d'une page spécifique d'un document (fichier Word, Excel, PPT ou PDF) directement dans le cloud, sans télécharger le fichier. Cette fonctionnalité répond à divers besoins, tels que l'intégration dans des pages web ou la sauvegarde de données.

Scénarios

  • Sauvegarde et récupération des données : créez régulièrement des instantanés des documents stockés dans vos buckets Object Storage Service (OSS) pour assurer leur sauvegarde.

  • Extraction d'informations clés : capturez une page spécifique via les instantanés de documents pour extraire rapidement les informations importantes.

Utilisation de cette fonctionnalité

Prérequis

Dans Object Storage Service (OSS), vous devez créer un bucket, télécharger le document à traiter dans ce bucket, puis associer un projet Intelligent Media Management (IMM) au bucket. Le projet IMM doit se trouver dans la même région que le bucket.

Instantanés de documents

Utilisez un SDK pour appeler l'API d'instantané de documents et traiter le fichier.

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);

Voici un exemple d'URL signée générée :

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

Copiez l'URL générée et collez-la dans la barre d'adresse de votre navigateur pour consulter l'instantané du document spécifié.

Paramètres

Action : doc/snapshot

Le tableau suivant décrit les paramètres.

Paramètre

Type

Obligatoire

Description

target

string

Non

Format cible de l'image. Valeurs possibles :

  • png (par défaut)

  • jpg

source

string

Non

Format de fichier du document source. Par défaut, l'extension du nom de l'objet est utilisée. Valeurs possibles :

  • pdf

  • xlsx

  • xls

  • docx

  • doc

  • pptx

  • ppt

Remarque

Si vous ne spécifiez pas ce paramètre et que l'objet ne possède pas d'extension de fichier, une erreur est renvoyée.

page

int

Non

Numéro de page du document. La valeur par défaut est 1 (première page). La valeur maximale est 2000.

Opérations API associées

Les opérations précédentes sont implémentées via des appels API. Si votre programme nécessite une personnalisation avancée, envoyez directement des requêtes REST API. Dans ce cas, vous devez écrire manuellement le code nécessaire au calcul de la signature. Pour plus d'informations sur le calcul de l'en-tête de requête commun Authorization, consultez Version 4 de la signature (recommandée).

Obtenir un instantané de la première page de example.docx

Méthode de traitement

Traitement par défaut

Exemple

// 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

Obtenir un instantané JPG de la deuxième page du document Word example

Méthode de traitement

  • target : jpg

  • source : docx

  • page : 2

Exemple

// 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

Autorisations

Un compte Alibaba Cloud dispose par défaut de toutes les autorisations. En revanche, un utilisateur RAM ou un rôle RAM associé à un compte Alibaba Cloud ne détient aucune autorisation par défaut. Le compte Alibaba Cloud ou un administrateur doit accorder les autorisations nécessaires via une politique RAM ou une politique de bucket.

API

Action

Description

GetObject

oss:GetObject

Télécharge un objet.

oss:GetObjectVersion

Lors du téléchargement d'un objet, si vous spécifiez la version de l'objet via versionId, cette autorisation est requise.

kms:Decrypt

Lors du téléchargement d'un objet, si les métadonnées de l'objet contiennent X-Oss-Server-Side-Encryption: KMS, cette autorisation est requise.

API

Action

Description

Aucune

oss:ProcessImm

Autorise l'utilisation des capacités de traitement des données d'IMM dans OSS.

API

Action

Description

CreateOfficeConversionTask

imm:CreateOfficeConversionTask

Autorisation d'utiliser IMM pour la conversion de documents ou la création d'instantanés.

Facturation

Les éléments facturables suivants s'appliquent aux instantanés de documents. Pour plus d'informations sur la tarification, consultez Tarification d'OSS et Éléments facturables :

API

Élément facturable

Description

GetObject

Requêtes GET

Des frais de requête sont appliqués en fonction du nombre de requêtes abouties.

Trafic sortant via Internet

Si vous appelez l'opération GetObject via un endpoint public (par exemple oss-cn-hangzhou.aliyuncs.com) ou un endpoint d'accélération (par exemple oss-accelerate.aliyuncs.com), des frais de trafic sortant via Internet sont appliqués en fonction du volume de données.

Récupération d'objets IA

Si des objets IA sont récupérés, des frais de récupération de données IA sont appliqués en fonction de la taille des données récupérées.

Récupération d'objets Archive dans un bucket avec accès en temps réel activé

Si vous récupérez des objets Archive dans un bucket pour lequel l'accès en temps réel est activé, des frais de récupération de données Archive sont appliqués en fonction de la taille des objets Archive récupérés.

Frais d'accélération de transfert

Si vous activez l'accélération de transfert et utilisez un endpoint d'accélération pour accéder à votre bucket, des frais d'accélération de transfert sont appliqués en fonction du volume de données.

API

Élément facturable

Description

CreateOfficeConversionTask

DocumentConvert

Des frais de requête sont appliqués en fonction du nombre de requêtes abouties.

Notes

  • Les instantanés de documents prennent uniquement en charge le traitement synchrone (méthode x-oss-process).

FAQ

Quelle est la taille maximale d'un document source pour un instantané de document ?

La taille maximale d'un document source pour un instantané de document est de 20 Mo.