La edición en línea de WebOffice le permite editar documentos de Word, presentaciones de PowerPoint y hojas de cálculo de Excel directamente en un navegador.
Casos de uso
Plataformas de oficina colaborativa: permiten que varios usuarios editen el mismo documento en tiempo real.
Sistemas de gestión de contenido: habilitan la edición de documentos en línea para crear, leer, actualizar y eliminar archivos directamente dentro del sistema.
Plataformas educativas: permiten a los estudiantes enviar tareas o a los profesores crear material didáctico, además de guardar documentos en la nube para facilitar su acceso y compartición.
Tipos de archivo compatibles
|
Tipo de archivo |
Extensiones |
|
Word |
doc, dot, wps, wpt, docx, dotx, docm, dotm |
|
PPT |
ppt, pptx, pptm, ppsx, ppsm, pps, potx, potm, dpt, dps |
|
Excel |
xls, xlt, et, xlsx, xltx, xlsm, xltm |
Notas de uso
Evite acceder a objetos de OSS entre regiones. Por ejemplo, si un archivo se almacena en un bucket en la región de Singapore pero se solicita desde China continental, las condiciones de red transfronteriza pueden degradar la calidad del enlace. Esto puede provocar un aumento en la latencia, fallos en la vista previa o conexiones inestables, lo cual afecta la estabilidad de la red y la experiencia del usuario. Para obtener un rendimiento óptimo, asegúrese de que el cliente y el bucket se encuentren en la misma región.
La edición en línea de WebOffice solo admite procesamiento síncrono mediante el parámetro
x-oss-process.
Cómo usar
Requisitos previos
En OSS, create a bucket, upload the Office document que desea editar al bucket y bind an Intelligent Media Management (IMM) project al bucket. El proyecto de IMM debe estar en la misma región que el bucket.
-
Debe access OSS by using a custom domain name.
NotaSi ve un mensaje que indica que el nombre de dominio no está en la lista de permitidos de WebView del mini programa, póngase en contacto con el soporte técnico de Intelligent Media Management (IMM) a través del grupo de DingTalk (ID: 88490020073). El equipo de soporte actualizará la lista de permitidos mediante el archivo de validación de dominio de confianza de WeChat que usted proporcione.
Generar una URL de edición
Java
Este ejemplo requiere Alibaba Cloud SDK for Java 3.17.4 o posterior. Para obtener más información sobre cómo instalar el SDK, consulte Installation.
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 {
// Specify your custom domain name. Example: http://static.example.com.
String endpoint = "http://static.example.com";
// Obtain credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. If the object is not in the root directory of the bucket, you must specify the full path.
String objectName = "exampledir/exampleobject.docx";
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient instance is no longer needed.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Set supportCname to true to enable CNAME.
clientBuilderConfiguration.setSupportCname(true);
// Explicitly declare that Signature Version 4 is used.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Specify document processing parameters.
String style = "doc/edit,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60";
// 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
Este ejemplo requiere Alibaba Cloud SDK for Python 2.18.4 o posterior. Para obtener más información sobre cómo instalar el SDK, consulte Installation (Python SDK V1).
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the bucket name.
bucket_name = 'examplebucket'
# Specify your custom domain name. Example: https://static.example.com.
endpoint = 'https://static.example.com'
# Specify the Alibaba Cloud region ID.
region = 'cn-hangzhou'
# Initialize the bucket using the custom domain name.
bucket = oss2.Bucket(auth, endpoint, bucket_name, is_cname=True, region=region)
# Specify the object to process.
key = 'example.docx'
# Specify the expiration time in seconds.
expire_time = 3600
# Construct the processing instruction for online editing.
image_process = 'doc/edit,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60'
# Generate a signed URL that contains processing parameters.
url = bucket.sign_url('GET', key, expire_time, params={'x-oss-process': image_process}, slash_safe=True)
# Print the signed URL.
print(url)
Go
Este ejemplo requiere Alibaba Cloud SDK for Go 3.0.2 o posterior. Para obtener más información sobre cómo instalar el SDK, consulte Install OSS Go SDK.
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The region.
bucketName string // The bucket name.
objectName string // The object name.
)
// The init function is used to initialize command-line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command-line parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configuration and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region).
// Specify your custom domain name. Example: http://static.example.com.
WithEndpoint("http://static.example.com").
WithUseCName(true)
// Create an OSS client.
client := oss.NewClient(cfg)
// Generate a presigned URL for GetObject.
result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
// Specify document processing parameters.
Process: oss.Ptr("doc/edit,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60"),
}, oss.PresignExpires(10*time.Minute))
if err != nil {
log.Fatalf("failed to get object presign %v", err)
}
log.Printf("request method:%v\n", result.Method)
log.Printf("request expiration:%v\n", result.Expiration)
log.Printf("request url:%v\n", result.URL)
if len(result.SignedHeaders) > 0 {
// If the response includes signed headers, you must include them in the GET request that uses the signed URL to prevent signature mismatch errors.
log.Printf("signed headers:\n")
for k, v := range result.SignedHeaders {
log.Printf("%v: %v\n", k, v)
}
}
}
Node.js
Este ejemplo requiere Alibaba Cloud SDK for Node.js 8.0 o posterior. Para obtener más información sobre cómo instalar el SDK, consulte Installation (Node.js SDK).
const OSS = require("ali-oss");
// Define a function to generate a signed URL.
async function generateSignatureUrl(fileName) {
// Obtain the signed URL.
const client = await new OSS({
// Specify your custom domain name. Example: http://static.example.com.
endpoint: 'http://static.example.com',
// Obtain credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
bucket: 'examplebucket',
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
authorizationV4: true,
cname: true
});
// Generate a signed URL that contains document processing parameters.
return await client.signatureUrlV4('GET', 3600, {
headers: {}, // Set request headers based on your actual request.
queries: {
"x-oss-process": "doc/edit,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60" // Add document processing parameters.
}
}, fileName);
}
// Call the function and pass a file name.
generateSignatureUrl('yourFileName').then(url => {
console.log('Generated Signature URL:', url);
}).catch(err => {
console.error('Error generating signature URL:', err);
});
PHP
Este ejemplo requiere Alibaba Cloud SDK for PHP 2.7.0 o posterior. Para obtener más información sobre cómo instalar el SDK, consulte Installation (PHP SDK V1).
<?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\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
// Obtain credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
//Specify your custom domain name. Example: http://static.example.com.
$endpoint = "http://static.example.com";
// Specify the bucket name. Example: examplebucket.
$bucket = "examplebucket";
// If the document is in the root directory of the bucket, specify only the document name. Otherwise, specify the full path. Example: exampledir/example.docx.
$object = 'example.docx';
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"cname" => true,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Generate a signed URL that contains processing parameters. The URL is valid for 3,600 seconds and can be directly accessed in a browser.
$timeout = 3600;
$options = array(
// Construct the processing instruction for online editing.
OssClient::OSS_PROCESS => "doc/edit,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60");
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("url: \n" . $signedUrl);
A continuación se muestra un ejemplo de una URL firmada generada:
http://static.example.com/example.docx?x-oss-process=doc%2Fedit%2Cexport_1%2Cprint_1%2Fwatermark%2Ctext_5YaF6YOo6LWE5paZ%2Csize_30%2Ct_60&x-oss-date=20250220T095032Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI********************%2F20250122%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=514ed93accdb80921c4b2897c6147fdb1599308c6457f68ee0ac2f771c7d0312
Copie la URL generada en la barra de direcciones de su navegador y presione Enter para abrir el documento y editarlo.
Parámetros
Acción: doc/edit
La siguiente tabla describe los parámetros.
Parámetro | Tipo | Obligatorio | Descripción |
int | No | Especifica si se permite la impresión. Valores válidos:
| |
export | int | No | Especifica si se permite la exportación a PDF. Valores válidos:
|
watermark | string | No | Los parámetros de la marca de agua. |
text | string | No | El texto de la marca de agua. El valor debe estar codificado en Base64 seguro para URL. Para obtener más información, consulte Watermark encoding. Se recomienda utilizar un codificador base64url. Padre: watermark |
size | int | No | El tamaño de fuente del texto de la marca de agua. El valor debe ser un número entero mayor que 0. Padre: watermark |
t | int | No | La opacidad del texto de la marca de agua. Valores válidos: de 0 a 100. Valor predeterminado: 100. Padre: watermark |
color | string | No | El color del texto de la marca de agua, especificado como un valor hexadecimal RGB. El valor predeterminado es #FFFFFF. Ejemplo: #000000 para negro y #FFFFFF para blanco. Padre: watermark |
rotate | int | No | El ángulo de rotación en sentido horario. Valores válidos: de 0 a 360. Valor predeterminado: 0. El valor predeterminado es 0, lo que indica que no hay rotación. Padre: watermark |
type | string | No | La fuente del texto de la marca de agua. El valor debe estar codificado en Base64 seguro para URL. Para obtener más información, consulte Watermark encoding. Se recomienda utilizar un codificador base64url. Se admiten las siguientes fuentes:
Padre: watermark |
Referencia de API
Las operaciones anteriores utilizan SDK. Para una mayor personalización, puede realizar solicitudes directas a la API REST, lo cual requiere calcular manualmente la firma. Para obtener información sobre cómo calcular el encabezado de solicitud Authorization, consulte Signature Version 4 (recommended).
Escenario de ejemplo
Documento a editar: example.docx
-
Información de la marca de agua para la página de edición:
Tipo de marca de agua: texto
Texto de la marca de agua: Material interno
Tamaño de fuente de la marca de agua: 30
Opacidad de la marca de agua: 60
Permisos para la página de edición: permitir exportación e impresión
Ejemplo de solicitud
GET /example.docx?x-oss-process=doc/edit,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60 HTTP/1.1
Host: doc-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue
Permisos
De forma predeterminada, una cuenta de Alibaba Cloud tiene todos los permisos. Los usuarios de RAM y los roles de RAM no tienen permisos por defecto. Una cuenta de Alibaba Cloud o un usuario de RAM con derechos administrativos debe otorgarles permisos mediante una RAM policy o un bucket policy.
API | Action | Descripción |
GetObject |
| Obligatorio para descargar un objeto. |
| Obligatorio cuando se descarga una versión específica de un objeto mediante el parámetro | |
| Obligatorio si el objeto está cifrado mediante SSE-KMS. |
|
API |
Action |
Descripción |
|
N/A |
|
Obligatorio para procesar datos mediante IMM a través de OSS. |
|
API |
Action |
Descripción |
|
GenerateWebofficeToken |
|
Obligatorio para obtener credenciales de WebOffice. |
|
RefreshWebofficeToken |
|
Obligatorio para actualizar credenciales de WebOffice. |
Facturación
La edición en línea de WebOffice genera cargos por los siguientes conceptos facturables. Para obtener detalles sobre los precios, consulte Precios de OSS y Billable items.
|
API |
Concepto facturable |
Descripción |
|
GetObject |
Solicitudes GET |
Se le cobran tarifas de solicitud según el número de solicitudes exitosas. |
|
Tráfico de salida a 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 le cobran tarifas por tráfico de salida a Internet según el tamaño de los datos. |
|
|
Recuperación de objetos IA |
Si se recuperan objetos IA, se le cobran tarifas de 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 le cobran tarifas de recuperación de datos Archive según el tamaño de los objetos Archive recuperados. |
|
|
Tarifas de aceleración de transferencia |
Si habilita la aceleración de transferencia y utiliza un endpoint de aceleración para acceder a su bucket, se le cobran tarifas de aceleración de transferencia según el tamaño de los datos. |
|
API |
Concepto facturable |
Descripción |
|
GenerateWebofficeToken |
DocumentWebofficeEdit |
Se le cobran tarifas de procesamiento de documentos según el número de llamadas a la API. Importante
Se le cobra por editar un documento en línea según el número de veces que se abre el documento para proyectos creados antes del 1 de diciembre de 2023, y según el número de llamadas a la API para proyectos creados en esa fecha o posteriores. |
|
RefreshWebofficeToken |