Bootstrap

onlyoffice api开发

编写代码

按照https://api.onlyoffice.com/editors/basic编写代码
API文档

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>01</title>
</head>
<body style="height: 100%;margin: 0;">
<div id="placeholder"></div>
<script type="text/javascript" src="http://10.10.90.139:8099/web-apps/apps/api/documents/api.js"></script>
<script type="text/javascript">
    config = {
        "document": {
            "fileType": "docx",
            "key": "CcauAgYYjWkLrMqqwACZ",
            "title": "测试01.docx",
            "url": "http://10.10.90.139:8849/uploads/onlyoffice01.docx"
        },
        "documentType": "word",
        "editorConfig": {
            "callbackUrl": ""
        }
    };
    var docEditor = new DocsAPI.DocEditor("placeholder", config);
</script>
</body>
</html>

其中http://10.10.90.139:8099是onlyoffice部署的地址
访问页面报错
在这里插入图片描述
两种解决方案

去掉jwt验证

将local.json里面 的token下的inbox、outbox、browser值改为false。

"token": { "enable": { "request": { "inbox": false, "outbox": false }, "browser": false },

然后重启下服务。命令:systemctl restart ds-*
windows下重启onlyoffice

添加token

新建asp.net core 空项目
安装JWT和Newtonsoft.json
在这里插入图片描述
修改Program

namespace OnlyOfficeStu02;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        builder.Services.AddControllers();
        var app = builder.Build();

        app.UseRouting();
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.MapControllers();
        app.Run();
    }
}

新建JwtManager

using JWT;
using JWT.Algorithms;
using JWT.Builder;
using JWT.Serializers;

namespace OnlyOfficeStu02.Utils;

public static class JwtManager
{
    private static readonly string Secret;
    public static readonly bool Enabled;
    public static readonly bool SignatureUseForRequest;

    static JwtManager()
    {
        Secret = "A4DgWFYPE6ILYOGH2tGlnkYeW0u1zp";  // get token secret from the config parameters
        Enabled = !string.IsNullOrEmpty(Secret);  // check if the token is enabled
        SignatureUseForRequest = true;
    }

    // encode a payload object into a token using a secret key
    public static string Encode(IDictionary<string, object> payload)
    {
        var encoder = new JwtEncoder(new HMACSHA256Algorithm(),
            new JsonNetSerializer(),
            new JwtBase64UrlEncoder());
        return encoder.Encode(payload, Secret);
    }

    public static string Encode(string payload)
    {
        var encoder = new JwtEncoder(new HMACSHA256Algorithm(),
            new JsonNetSerializer(),
            new JwtBase64UrlEncoder());
        return encoder.Encode(payload, Secret);
    }
    
    // decode a token into a payload object using a secret key
    public static string Decode(string token)
    {
        if (!Enabled || string.IsNullOrEmpty(token)) return "";

        return JwtBuilder.Create()
            .WithAlgorithm(new HMACSHA256Algorithm())
            .WithSecret(Secret)
            .MustVerifySignature()
            .Decode(token);
    }
}

新建IndexController

using Microsoft.AspNetCore.Mvc;
using OnlyOfficeStu02.Models;
using OnlyOfficeStu02.Utils;

namespace OnlyOfficeStu02.Controllers;

/// <summary>
/// 首页控制器
/// </summary>
[ApiController]
[Route("[Controller]/[Action]")]
public class IndexController : ControllerBase
{
    /// <summary>
    /// 构造函数注入
    /// </summary>
    public IndexController()
    {
    }

    /// <summary>
    /// jwt编码
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    [HttpPost]
    public IActionResult JwtEncode([FromBody]JwtEncodeParamModel param)
    {
        var jwtStr = JwtManager.Encode(param.JsonStr);
        return new JsonResult(new JwtEncodeViewModel
        {
            Jwt = jwtStr
        });
    }
    
    /// <summary>
    /// 回调相应
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public IActionResult CallBack()
    {
        var res = new CallBackViewModel();
        res.Error = 0;
        return new JsonResult(res);
    }
}

wwwroot下新增index.html

文档的编辑

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>01</title>
</head>
<body style="height: 100%;margin: 0;">
<div id="placeholder"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script type="text/javascript" src="http://10.10.90.139:8099/web-apps/apps/api/documents/api.js"></script>
<script type="text/javascript">
    const config = {
        "document": {
            "fileType": "docx",
            "key": "CcauAgYYjWkLrMqqwACZ",
            "title": "测试01.docx",
            "url": "http://10.10.90.139:8849/uploads/onlyoffice01.docx",
            // 权限,每个要打开的文档都可以设置独立的权限
            "permissions": {
                // 启用评论
                "comment": false,
                // 启用下载
                "download": false,
                // 启用编辑
                "edit": false,
                // 启用导出
                "print": false,
                // 启用预览
                "review": true
            }
        },
        "documentType": "word",
        "editorConfig": {
            "callbackUrl": "/index/callback",
            // 设置语言
            "lang": "zh-CN",
            // 添加用户信息
            "user": {
                "group": "技术部",
                "id": "wjl",
                "name": "wjl"
            },
        }
    };
    $(function () {
        const configJsonStr = JSON.stringify(config);
        $.ajax({
            type: "POST",
            url: "/index/jwtencode",
            contentType: "application/json",
            data: JSON.stringify({
                "jsonStr":configJsonStr
            }),
            dataType: "json",
            success: function (data) {
                console.log("成功")
                console.log(data)
                if(data.jwt){
                    config.token = data.jwt;
                    var docEditor = new DocsAPI.DocEditor("placeholder", config);
                }
            },
            error: function (err) {
                console.error(err);
            }
        })
        
    })
</script>
</body>
</html>

启动项目访问
在这里插入图片描述

文档的预览

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>01</title>
</head>
<body style="height: 100%;margin: 0;">
<div id="placeholder"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script type="text/javascript" src="http://10.10.90.139:8099/web-apps/apps/api/documents/api.js"></script>
<script type="text/javascript">
    const config = {
        "document": {
            "fileType": "docx",
            "key": "CcauAgYYjWkLrMqqwACZ",
            "title": "测试01.docx",
            "url": "http://10.10.90.139:8849/uploads/onlyoffice01.docx",
            // 权限,每个要打开的文档都可以设置独立的权限
            "permissions": {
                // 启用评论
                "comment": false,
                // 启用下载
                "download": true,
                // 启用编辑
                "edit": false,
                // 启用导出
                "print": false,
                // 启用预览
                "review": true,
                //是否开启聊天
                "chat": false,
                //是否可以复制
                "copy": true,
                //是否文档受保护
                "protect": true,
                
                "fillForms": false,
            }
        },
        "documentType": "word",
        "editorConfig": {
            "callbackUrl": "/index/callback",
            // 设置语言
            "lang": "zh-CN",
            "mode":"view",//edit 或者view
            // 添加用户信息
            "user": {
                "group": "技术部",
                "id": "wjl",
                "name": "wjl"
            },
        }
    };
    $(function () {
        const configJsonStr = JSON.stringify(config);
        $.ajax({
            type: "POST",
            url: "/index/jwtencode",
            contentType: "application/json",
            data: JSON.stringify({
                "jsonStr":configJsonStr
            }),
            dataType: "json",
            success: function (data) {
                console.log("成功")
                console.log(data)
                if(data.jwt){
                    config.token = data.jwt;
                    var docEditor = new DocsAPI.DocEditor("placeholder", config);
                }
            },
            error: function (err) {
                console.error(err);
            }
        })

    })
</script>
</body>
</html>

在这里插入图片描述

注意:如果只是预览,远程的word不会下载带onlyoffice服务器上,但是如果有下载或者编辑则会下载到onlyoffice服务器上

参考

token获取
常见问题
常见问题中文
java问题
onlyoffice jwt
onlyoffice jwt
onlyoffice 签名

;