OnlyOffice集成Springboot以及web端

上次我们已经搭建好了onlyoffice的服务,不知道如何搭建的伙伴可以看看上篇文章。

以下是springboot和前端web简单集成的页面,亲测jdk8和jdk17都适用。

结构

在这里插入图片描述

前端页面

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="${title}"></title>
</head>
<body>

<div id="fileEdit"></div>
<!--// 页面引入document的api.js-->
<script type="text/javascript" src="http://192.168.188.38:8088/web-apps/apps/api/documents/api.js"></script>
<script>
    // 调用js创建预览对象
//     new DocsAPI.DocEditor("fileEdit", // 元素id
//         {
//             "document": {
//                 "permissions": {
//                     "edit": true,
//                 },
//                 "fileType": "docx", // 展示文件的类型
//                 "title": "页面展示的文件名称",
//                 "url":"http://192.168.124.99/static/alllink/111.docx" //读取文件进行展示
//             },
//             "documentType": "text",
//             "editorConfig": {
//                 "lang" : "zh-CN",
// // 回调接口,用于编辑后实现保存的功能,(关闭页面5秒左右会触发)
//                 "callbackUrl": "http://192.168.124.37:8080/docx/save?path=C:\\Users\\hdx\\Desktop\\111.docx" //保存文件的接口?path=告诉保存接口需要覆盖的文件
//             },
//             "height": "1000px",
//             "width": "100%"
//         })

    // new DocsAPI.DocEditor("fileEdit", // 元素id
    //     {
    //         "document": {
    //             "permissions": {
    //                 "edit": true,
    //             },
    //             "fileType": "[[${type}]]", // 展示文件的类型 "xlsx"
    //             "title": "页面展示的文件名称",
    //             // "url":"http://192.168.100.104:9090/test/111.docx" //读取文件进行展示  http://192.168.124.99/static/alllink/file/039adc7b92ce1000/039adc7b92ce1000.xlsx
    //             "url":"http://192.168.100.133:8080/d" //读取文件进行展示  http://192.168.124.99/static/alllink/file/039adc7b92ce1000/039adc7b92ce1000.xlsx
    //         },
    //         // "key":'',
    //         "documentType": "word",//
    //         "editorConfig": {
    //             "lang" : "zh-CN",
    //             // 回调接口,用于编辑后实现保存的功能,(关闭页面5秒左右会触发)
    //             "callbackUrl": "http://192.168.100.133:8080/docx/save?id="+[[${id}]],//保存文件的接口?path=告诉保存接口需要覆盖的文件
    //             "user":{
    //                 "id":"1111",
    //                 "name":"hdx"
    //             }
    //         },
    //         "height": "1000px",
    //         "width": "100%"
    //     })

    new DocsAPI.DocEditor("fileEdit", // 元素id
        {
            type: "desktop",
            width: "100%",
            height: "1000px",
            document: {
                title: "aaaa",
                url: "http://192.168.188.125:8080/d",
                fileType:"docx",
                key: "",
                lang: "zh-CN",
                permissions: {
                    "download": true,
                    "edit": true,
                    "fillForms": true,
                    "print": true,
                }
            },
            editorConfig: {
                "lang": "zh-CN",
                mode: "edit",
                "callbackUrl": "http://192.168.188.125:8080/docx/save?id=1111",
                "coEditing": {
                    "mode": "fast",
                    "change": true
                },
                "customization": {
                    "toolbarNoTabs": true,
                    "autosave": true,
                    "forcesave": true,
                    "hideRightMenu": true,
                },
                //用户信息
                "user": {
                    "id": "001", //用户ID
                    "name": "测试" //用户全名称
                }
            }
        });
</script>
</body>
</html>

就是引入了onlyoffice的api

在这里插入图片描述
将地址改为自己搭建的onlioffice服务地址
在这里插入图片描述
改为相应的本机地址

springboot

文档下载

 @RequestMapping("/d")
    public String downExcel(HttpServletResponse response) throws UnsupportedEncodingException {
        File file = new File("F:\\Desktop\\111.docx");
        // 如果文件存在,则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("aaa.doc", "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download  successfully!");
                return "successfully";

            } catch (Exception e) {
                System.out.println("Download  failed!");
                return "failed";

            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "";
    }

保存修改

/**
     * 保存修改后的
     * @param request
     * @param response
     */
    @PostMapping("/docx/save")
    public void saveWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            PrintWriter writer = response.getWriter();
            String body = "";
            try {
                Scanner scanner = new Scanner(request.getInputStream());
                scanner.useDelimiter("\\A");
                body = scanner.hasNext() ? scanner.next() : "";
                scanner.close();
            } catch (Exception ex) {
                writer.write("get request.getInputStream error:" + ex.getMessage());
                return;
            }
            if (body.isEmpty()) {
                writer.write("empty request.getInputStream");
                return;
            }
            JSONObject jsonObj = JSON.parseObject(body);
            int status = (Integer) jsonObj.get("status");
            int saved = 0;
            if (status == 2 || status == 3)//MustSave, Corrupted
            {
                String downloadUri = (String) jsonObj.get("url");
                try {
                    URL url = new URL(downloadUri);
                    java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                    InputStream stream = connection.getInputStream();
                    if (stream == null) {
                        throw new Exception("Stream is null");
                    }
                    // 从请求中获取要覆盖的文件参数定义"path"
//                    String path = request.getParameter("path");
                    String path = "F:\\Desktop\\111.docx";
                    System.err.println("====路径:"+path);
                    File savedFile = new File(path);
                    try (FileOutputStream out = new FileOutputStream(savedFile)) {
                        int read;
                        final byte[] bytes = new byte[1024];
                        while ((read = stream.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }
                        out.flush();
                    }
                    connection.disconnect();
                } catch (Exception ex) {
                    saved = 1;
                    ex.printStackTrace();
                }
            }
            System.out.print("编辑完成--------------11111");
            writer.write("{\"error\":" + saved + "}");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

也就是给个基础的demo,更多的操作参考官网api哈

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要将ONLYOFFICE集成Spring Boot项目中,您可以按照以下步骤操作: 1. 首先,确保您已经安装了Java和Spring Boot的开发环境,并创建了一个空的Spring Boot项目。 2. 下载 ONLYOFFICE Document Server(https://www.onlyoffice.com/download.aspx)并进行安装。 3. 在您的Spring Boot项目的依赖管理文件(例如pom.xml)中添加ONLYOFFICE Document Server的依赖项。您可以通过以下方式添加依赖: ```xml <dependency> <groupId>com.onlyoffice</groupId> <artifactId>onlyoffice-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> ``` 4. 在您的Spring Boot项目中创建一个配置类,并配置ONLYOFFICE Document Server的相关参数。在该类上使用`@Configuration`注解,并在方法上使用`@Bean`注解创建`OnlyOfficeConfig` bean。例如: ```java @Configuration public class OnlyOfficeConfig { @Value("${onlyoffice.server.url}") private String serverUrl; @Value("${onlyoffice.secret.key}") private String secretKey; @Bean public OnlyOfficeApi onlyOfficeApi() { return new OnlyOfficeApi(serverUrl, secretKey); } } ``` 在上面的示例中,`serverUrl`是ONLYOFFICE Document Server的URL,`secretKey`是用于与Document Server进行通信的密钥。 5. 创建一个Controller类,处理与ONLYOFFICE Document Server的交互。您可以在该类中定义各种操作,例如创建、编辑和保存文档。在该类上使用`@RestController`注解,并在方法上使用相应的请求映射注解(例如`@PostMapping`)。 ```java @RestController public class DocumentController { private final OnlyOfficeApi onlyOfficeApi; public DocumentController(OnlyOfficeApi onlyOfficeApi) { this.onlyOfficeApi = onlyOfficeApi; } @PostMapping("/createDocument") public ResponseEntity<String> createDocument() { // 在此处处理创建文档的逻辑 } @PostMapping("/saveDocument") public ResponseEntity<String> saveDocument() { // 在此处处理保存文档的逻辑 } // 其他操作... } ``` 在上面的示例中,通过构造函数注入`OnlyOfficeApi` bean,以便与ONLYOFFICE Document Server进行通信。 请注意,上述代码仅为示例,并且您需要根据您的需求进行适当的更改和扩展。 希望这可以帮助您将ONLYOFFICE集成Spring Boot项目中!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杵意

谢谢金主打赏呀!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值