Springboot Vue element-ui前后端分离实现onlyoffice在线协同编辑Demo

wylc123 1年前 ⋅ 3404 阅读

后端代码:

最主要的就是回调函数:
/**
 * @author SongBin on 2021/4/26.
   @website https://www.daxueyiwu.com
 */
package com.qiwenshare.file.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qiwenshare.common.config.QiwenFileConfig;
import com.qiwenshare.common.exception.NotLoginException;
import com.qiwenshare.common.result.RestResult;
import com.qiwenshare.common.util.DateUtil;
import com.qiwenshare.common.util.FileUtil;
import com.qiwenshare.common.util.PathUtil;
import com.qiwenshare.file.anno.MyLog;
import com.qiwenshare.file.api.IFileService;
import com.qiwenshare.file.api.IFiletransferService;
import com.qiwenshare.file.api.IUserFileService;
import com.qiwenshare.file.api.IUserService;
import com.qiwenshare.file.domain.*;
import com.qiwenshare.file.dto.file.CreateFileDTO;
import com.qiwenshare.file.dto.file.OnlyofficeDTO;
import com.qiwenshare.file.util.ConfigManager;
import io.netty.util.internal.StringUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;

@Tag(name = "office", description = "该接口为Onlyoffice文件操作接口,主要用来做一些文档的编辑,浏览等。")
@RestController
@Slf4j
@RequestMapping("/office")
public class OnlyOfficeController {
    public static final String CURRENT_MODULE = "Onlyoffice文件操作接口";
    @Resource
    IUserService userService;

    @Resource
    QiwenFileConfig qiwenFileConfig;
//    @Value("${onlyoffice.apijs}")
//    private String docserviceApiUrl;
    private String docserviceApiUrl = ConfigManager.GetProperty("files.docservice.url.api");
//    @Value("${onlyoffice.plugins}")
//    private String[] pluginsDatas;
    private String pluginsDatas = ConfigManager.GetProperty("files.docservice.url.api");
    @Value("${deployment.onServer}")
    private boolean onServer;
    @Value("${deployment.apiPath}")
    private String apiPath;
    @Value("${deployment.isNeedIntranet}")
    private boolean isNeedIntranet;
    @Value("${deployment.intranetUrl}")
    private String intranetUrl;
    @Value("${deployment.outnetUrl}")
    private String outnetUrl;
    @Value("${deployment.sslconfig}")
    private String sslconfig;
    @Value("${deployment.pagenetUrl}")
    private String pagenetUrl;

    @Resource
    IFileService fileService;
    @Resource
    IFiletransferService filetransferService;
    @Resource
    IUserFileService userFileService;

    @ResponseBody
    @RequestMapping(value = "/createReportForOnlyofficeApi_bak", method = RequestMethod.POST)
    public RestResult<Object> createReportForOnlyofficeApi_bak(HttpServletRequest request, @RequestBody OnlyofficeDTO onlyofficeDTO, @RequestHeader("token") String token) {
        RestResult<Object> result = new RestResult<>();
        try{
            if (!operationCheck(token).getSuccess()){
                return operationCheck(token);
            }
            UserBean loginUser = userService.getUserBeanByToken(token);
            if (loginUser == null) {
                throw new NotLoginException();
            }

            List<UserFile> userFiles = userFileService.selectUserFileByNameAndPath(onlyofficeDTO.getFileName(), onlyofficeDTO.getFilePath(), loginUser.getUserId());
            if (userFiles != null && !userFiles.isEmpty()) {
                return RestResult.fail().message("同名文件已存在");
            }
            String baseDir = FileUtil.getLocalFileSavePath();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String fileUrl = baseDir + uuid + onlyofficeDTO.getExtendName();
            String fileName = onlyofficeDTO.getFileName();
            String filePath = onlyofficeDTO.getFilePath();
            onlyofficeDTO.setType("track");
            onlyofficeDTO.setFileUrl(onlyofficeDTO.getFileUrl()+fileUrl);
            onlyofficeDTO.setFileName(onlyofficeDTO.getFileName()+ "." + onlyofficeDTO.getExtendName());
            String staticPath = PathUtil.getStaticPath();
            String initFilePath = staticPath + fileUrl;
            onlyofficeDTO.setFilePath(initFilePath);
            String contextPath = onServer?apiPath:"";
            String baseUrl = isNeedIntranet ? intranetUrl :request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
            baseUrl =baseUrl + contextPath;
            OnlyofficeFileModel file = new OnlyofficeFileModel(loginUser,onlyofficeDTO,"edit");
            String[] pluginsDatasArr = pluginsDatas.split(",");
            file.editorConfig.plugins.pluginsData = pluginsDatasArr;
            String query = null;
            try {
                query = "?type=track&fileName=" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString())
                        + "&fileUrl=" + fileUrl
                        + "&uuid=" + uuid
                        + "&filePath=" + filePath
                        + "&extendName=" + onlyofficeDTO.getExtendName()
                ;
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
            file.editorConfig.callbackUrl= baseUrl + "/office/IndexServlet" + query;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("file",file);
            jsonObject.put("docserviceApiUrl",docserviceApiUrl);
            jsonObject.put("reportName",fileName);
            result.setData(jsonObject);
            result.setCode(200);
            result.setMessage("创建报告成功!");
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setCode(500);
            result.setMessage("服务器错误!");
        }
        return result;
    }
    //创建新文件接口
    @ResponseBody
    @RequestMapping(value = "/createReportForOnlyofficeApi", method = RequestMethod.POST)
    public RestResult<Object> createReportForOnlyofficeApi(HttpServletRequest request, @RequestBody OnlyofficeDTO onlyofficeDTO, @RequestHeader("token") String token) {
        RestResult<Object> result = new RestResult<>();
        try{
            if (!operationCheck(token).getSuccess()){
                return operationCheck(token);
            }
            UserBean loginUser = userService.getUserBeanByToken(token);
            if (loginUser == null) {
                throw new NotLoginException();
            }

            List<UserFile> userFiles = userFileService.selectUserFileByNameAndPath(onlyofficeDTO.getFileName(), onlyofficeDTO.getFilePath(), loginUser.getUserId());
            if (userFiles != null && !userFiles.isEmpty()) {
                return RestResult.fail().message("同名文件已存在");
            }
            String baseDir = FileUtil.getLocalFileSavePath();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String fileUrl = baseDir + uuid + "." + onlyofficeDTO.getExtendName();
            String fileName = onlyofficeDTO.getFileName();
            String filePath = onlyofficeDTO.getFilePath();
            String extendName = onlyofficeDTO.getExtendName();
            //创建空文件
            String staticPath = PathUtil.getStaticPath();
            String initFilePath = staticPath + fileUrl;
            onlyofficeDTO.setFilePath(initFilePath);
            File file = new File(initFilePath);
            if(!file.exists()){
                try {
                    if("docx".equals(extendName)){
                        //创建word文档
                        XWPFDocument document= new XWPFDocument();
                        //Write the Document in file system
                        FileOutputStream out = new FileOutputStream(file);
                        document.write(out);
                        out.close();
                    }else if("xlsx".equals(extendName)){
                        //创建excel表格
                         XSSFWorkbook workbook = new XSSFWorkbook();
                         //创建工作表
                         workbook.createSheet("Sheet1");
                        //Write the Document in file system
                        FileOutputStream out = new FileOutputStream(file);
                        workbook.write(out);
                        out.close();
                    }else if("pptx".equals(extendName)){
                        //创建pptx演示文稿
                        XMLSlideShow pptx = new XMLSlideShow();
                        //创建工作表
                        //Write the Document in file system
                        FileOutputStream out = new FileOutputStream(file);
                        pptx.write(out);
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileBean fileBean = new FileBean();
            fileBean.setFileSize(Long.valueOf(0));
            fileBean.setFileUrl(fileUrl);
            fileBean.setIsOSS(0);
            fileBean.setStorageType(0);
            fileBean.setPointCount(1);
            fileBean.setIdentifier(uuid);
            fileBean.setTimeStampName(uuid);
            boolean saveFlag = fileService.save(fileBean);
            UserFile userFile = new UserFile();
            if(saveFlag) {
                userFile.setUserId(loginUser.getUserId());
                userFile.setFileName(fileName);
                userFile.setFilePath(filePath);
                userFile.setDeleteFlag(0);
                userFile.setIsDir(0);
                userFile.setExtendName(extendName);
                userFile.setUploadTime(DateUtil.getCurrentTime());
                userFile.setFileId(fileBean.getFileId());
                boolean ufsaveFlag = userFileService.save(userFile);
            }
            Long newFileSize = file.length();
            //更新文件修改信息
            LambdaUpdateWrapper<UserFile> userFileUpdateWrapper = new LambdaUpdateWrapper<>();
            userFileUpdateWrapper
                    .set(UserFile::getUploadTime, DateUtil.getCurrentTime())
                    .eq(UserFile::getUserFileId, userFile.getUserFileId());
            userFileService.update(userFileUpdateWrapper);
            LambdaUpdateWrapper<FileBean> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            FileInputStream fins = new FileInputStream(staticPath + filePath);
            String md5Str = DigestUtils.md5Hex(fins);
            fins.close();
            // 修改空间剩余量
            StorageBean storageBean = filetransferService.selectStorageBean(new StorageBean(loginUser.getUserId()));
            if (storageBean == null) {
                StorageBean storage = new StorageBean(loginUser.getUserId());
                storage.setStorageSize(newFileSize);
                filetransferService.insertStorageBean(storage);
            } else {
                storageBean.setStorageSize(storageBean.getStorageSize() + newFileSize);
                filetransferService.updateStorageBean(storageBean);
            }
//                    String newFileUrl = filePath.replaceAll(identifier,md5Str);
//                    String newFilePath = staticPath + newFileUrl;
//                    boolean flag = FileUtil.renameFile(oldFilePath, newFilePath);
//                    if(flag){
            lambdaUpdateWrapper
//                                .set(FileBean::getFileUrl, newFileUrl)
                    .set(FileBean::getIdentifier, md5Str)
                    .set(FileBean::getTimeStampName, md5Str)
                    .set(FileBean::getFileSize, newFileSize)
                    .eq(FileBean::getFileId, fileBean.getFileId());
            fileService.update(lambdaUpdateWrapper);
//                    }
            result.success();
            result.setMessage("文件创建成功!");
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setCode(500);
            result.setMessage("服务器错误!");
        }
        return result;
    }

    // 查看报告接口
    @Operation(summary = "查看报告接口", description = "查看报告接口", tags = {"showReportForOnlyofficeApi"})
    @MyLog(operation = "查看报告接口", module = CURRENT_MODULE)
    @RequestMapping(value = "/showReportForOnlyofficeApi", method = RequestMethod.POST)
    @ResponseBody
    public RestResult<Object> showReportForOnlyofficeApi(HttpServletRequest request, @RequestBody OnlyofficeDTO onlyofficeDTO, @RequestHeader("token") String token) {
        RestResult<Object> result = new RestResult<>();
        try {
            if (!operationCheck(token).getSuccess()){
                return operationCheck(token);
            }
            UserBean loginUser = userService.getUserBeanByToken(token);
            if (loginUser == null) {
                throw new NotLoginException();
            }
            String fileUrl = onlyofficeDTO.getFileUrl();
//            String fName = fileUrl.trim();
//            String temp[] = fName.split("/"); /**split里面必须是正则表达式,"\\"的作用是对字符串转义*/
//            String fileName = temp[temp.length-1];
            String fileName = onlyofficeDTO.getFileName();
            String contextPath = onServer?apiPath:"";
            String baseUrl = isNeedIntranet ? intranetUrl :request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
            baseUrl =baseUrl + contextPath;
            OnlyofficeFileModel file = new OnlyofficeFileModel(loginUser,onlyofficeDTO,"view");
            String query = "?type=show&token="+token;
            file.editorConfig.callbackUrl= baseUrl + "/office/IndexServlet" + query;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("file",file);
            jsonObject.put("docserviceApiUrl",docserviceApiUrl);
            jsonObject.put("reportName",fileName);
            result.setData(jsonObject);
            result.setCode(200);
            result.setMessage("获取报告成功!");
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setCode(500);
            result.setMessage("服务器错误!");
        }
        return result;
    }

    //编辑报告接口
    @ResponseBody
    @RequestMapping(value = "/editReportForOnlyofficeApi", method = RequestMethod.POST)
    public RestResult<Object> editReportForOnlyofficeApi(HttpServletRequest request,@RequestBody OnlyofficeDTO onlyofficeDTO, @RequestHeader("token") String token) {
        RestResult<Object> result = new RestResult<>();
        try {
            if (!operationCheck(token).getSuccess()){
                return operationCheck(token);
            }
            UserBean loginUser = userService.getUserBeanByToken(token);
            if (loginUser == null) {
                throw new NotLoginException();
            }
            String fileId = onlyofficeDTO.getFileId();
            String fileName = onlyofficeDTO.getFileName();
            String contextPath = onServer?apiPath:"";
            String baseUrl = isNeedIntranet ? intranetUrl :request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
            baseUrl =baseUrl + contextPath;
            OnlyofficeFileModel file = new OnlyofficeFileModel(loginUser,onlyofficeDTO,"edit");
            String query = "?type=edit&fileId="+fileId+"&token="+token;
            file.editorConfig.callbackUrl= baseUrl + "/office/IndexServlet" + query;

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("file",file);
            jsonObject.put("docserviceApiUrl",docserviceApiUrl);
            jsonObject.put("reportName",fileName);
            result.setData(jsonObject);
            result.setCode(200);
            result.setMessage("编辑报告成功!");
        } catch (Exception e) {
            log.error(e.getMessage());
            result.setCode(500);
            result.setMessage("服务器错误!");
        }
        return result;
    }


    @RequestMapping(value = "/IndexServlet", method = RequestMethod.POST)
    @ResponseBody
    public void IndexServlet(HttpServletResponse response, HttpServletRequest request) throws IOException {
        RestResult<Object> result = new RestResult<>();
        String token = request.getParameter("token");
        UserBean loginUser = userService.getUserBeanByToken(token);
        if (loginUser == null) {
            throw new NotLoginException();
        }
        PrintWriter writer = null;
        JSONObject jsonObj=null;
        log.debug("===save edited file------------");
        try {
            writer = response.getWriter();
            Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
            String body = scanner.hasNext() ? scanner.next() : "";

            jsonObj = JSON.parseObject(body);
            log.debug("===saveeditedfile:" + jsonObj.get("status")) ;
            String status = jsonObj!=null?jsonObj.get("status").toString():"";
            if ("6".equals(status)) {//新建报告不强制手动操作时状态为2
                String type = request.getParameter("type");
                String downloadUri = (String) jsonObj.get("url");
                downloadUri = downloadUri.replaceAll("http://",sslconfig);
                //if(isNeedIntranet) {
                //	downloadUri = downloadUri.replaceAll(outnetUrl, intranetUrl);
                //}
                if("track".equals(type)){
                    log.debug("====文档编辑完成,现在开始保存编辑后的文档,其下载地址为:" + downloadUri);
                    String fileUrl = request.getParameter("fileUrl");
                    String uuid = request.getParameter("uuid");
                    String filePath = request.getParameter("filePath");
                    String fileName = request.getParameter("fileName");
                    String extendName = request.getParameter("extendName");
                    URL url = new URL(downloadUri);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    InputStream stream = connection.getInputStream();
                    String staticPath = PathUtil.getStaticPath();
                    String oldFilePath = staticPath + fileUrl;
                    File oldFile = new File(oldFilePath);
                    Long oldFileSize = oldFile.length();
                    try (FileOutputStream out = new FileOutputStream(oldFile)) {
                        int read;
                        final byte[] bytes = new byte[1024];
                        while ((read = stream.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }
                        out.flush();
                    }
                    connection.disconnect();
                    FileBean fileBean = new FileBean();
                    fileBean.setFileSize(Long.valueOf(0));
                    fileBean.setFileUrl(fileUrl);
                    fileBean.setIsOSS(0);
                    fileBean.setStorageType(0);
                    fileBean.setPointCount(1);
                    fileBean.setIdentifier(uuid);
                    fileBean.setTimeStampName(uuid);
                    boolean saveFlag = fileService.save(fileBean);
                    UserFile userFile = new UserFile();
                    if(saveFlag) {
                        userFile.setUserId(loginUser.getUserId());
                        userFile.setFileName(fileName);
                        userFile.setFilePath(filePath);
                        userFile.setDeleteFlag(0);
                        userFile.setIsDir(0);
                        userFile.setExtendName(extendName);
                        userFile.setUploadTime(DateUtil.getCurrentTime());
                        userFile.setFileId(fileBean.getFileId());
                        boolean ufsaveFlag = userFileService.save(userFile);
                    }
                    Long newFileSize = oldFile.length();
                    //更新文件修改信息
                    LambdaUpdateWrapper<UserFile> userFileUpdateWrapper = new LambdaUpdateWrapper<>();
                    userFileUpdateWrapper
                            .set(UserFile::getUploadTime, DateUtil.getCurrentTime())
                            .eq(UserFile::getUserFileId, userFile.getUserFileId());
                    userFileService.update(userFileUpdateWrapper);
                    LambdaUpdateWrapper<FileBean> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    FileInputStream fins = new FileInputStream(staticPath + filePath);
                    String md5Str = DigestUtils.md5Hex(fins);
                    fins.close();
                    // 修改空间剩余量
                    StorageBean storageBean = filetransferService.selectStorageBean(new StorageBean(loginUser.getUserId()));
                    if (storageBean == null) {
                        StorageBean storage = new StorageBean(loginUser.getUserId());
                        storage.setStorageSize(newFileSize);
                        filetransferService.insertStorageBean(storage);
                    } else {
                        storageBean.setStorageSize(storageBean.getStorageSize() + (newFileSize - oldFileSize));
                        filetransferService.updateStorageBean(storageBean);
                    }
//                    String newFileUrl = filePath.replaceAll(identifier,md5Str);
//                    String newFilePath = staticPath + newFileUrl;
//                    boolean flag = FileUtil.renameFile(oldFilePath, newFilePath);
//                    if(flag){
                    lambdaUpdateWrapper
//                                .set(FileBean::getFileUrl, newFileUrl)
                            .set(FileBean::getIdentifier, md5Str)
                            .set(FileBean::getTimeStampName, md5Str)
                            .set(FileBean::getFileSize, newFileSize)
                            .eq(FileBean::getFileId, fileBean.getFileId());
                    fileService.update(lambdaUpdateWrapper);
//                    }
                }else if("show".equals(type)){//查看报告
                    log.debug("====只查看不保存:");
                }else if("edit".equals(type)){//修改报告
                    log.debug("====文档编辑完成,现在开始保存编辑后的文档,其下载地址为:" + downloadUri);
                    String fileId = request.getParameter("fileId");
                    String userFileId = request.getParameter("userFileId");
                    FileBean fileBean = fileService.getById(fileId);
                    String filePath = fileBean.getFileUrl();
                    String identifier = fileBean.getIdentifier();
                    URL url = new URL(downloadUri);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    InputStream stream = connection.getInputStream();
                    String staticPath = PathUtil.getStaticPath();
                    String oldFilePath = staticPath + filePath;
                    File oldFile = new File(oldFilePath);
                    Long oldFileSize = oldFile.length();
                    try (FileOutputStream out = new FileOutputStream(oldFile)) {
                        int read;
                        final byte[] bytes = new byte[1024];
                        while ((read = stream.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }
                        out.flush();
                    }
                    connection.disconnect();
                    Long newFileSize = oldFile.length();
                    //更新文件修改信息
                    LambdaUpdateWrapper<UserFile> userFileUpdateWrapper = new LambdaUpdateWrapper<>();
                    userFileUpdateWrapper
                            .set(UserFile::getUploadTime, DateUtil.getCurrentTime())
                            .eq(UserFile::getUserFileId, userFileId);
                    userFileService.update(userFileUpdateWrapper);
                    LambdaUpdateWrapper<FileBean> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    FileInputStream fins = new FileInputStream(staticPath + filePath);
                    String md5Str = DigestUtils.md5Hex(fins);
                    fins.close();
                    // 修改空间剩余量
                    StorageBean storageBean = filetransferService.selectStorageBean(new StorageBean(loginUser.getUserId()));
                    if (storageBean == null) {
                        StorageBean storage = new StorageBean(loginUser.getUserId());
                        storage.setStorageSize(newFileSize);
                        filetransferService.insertStorageBean(storage);
                    } else {
                        storageBean.setStorageSize(storageBean.getStorageSize() + (newFileSize - oldFileSize));
                        filetransferService.updateStorageBean(storageBean);
                    }
//                    String newFileUrl = filePath.replaceAll(identifier,md5Str);
//                    String newFilePath = staticPath + newFileUrl;
//                    boolean flag = FileUtil.renameFile(oldFilePath, newFilePath);
//                    if(flag){
                        lambdaUpdateWrapper
//                                .set(FileBean::getFileUrl, newFileUrl)
                                .set(FileBean::getIdentifier, md5Str)
                                .set(FileBean::getTimeStampName, md5Str)
                                .set(FileBean::getFileSize, newFileSize)
                                .eq(FileBean::getFileId, fileId);
                        fileService.update(lambdaUpdateWrapper);
//                    }
//                    //保存到表中 报告
//                    if("report".equals(doctype)){
//                        /*添加报告*/
//                        Report report = reportService.getByID(Integer.valueOf(id));
//                        int flag_up = 0;
//                        report.setModifyUser(UserCode);
//                        Date day=new Date();
//                        report.setModifyTime(day);
//                        flag_up = reportService.updateReportInfo(report);
//                    }else if("reportTemplet".equals(doctype)){
//                        /*添加报告模板*/
//                        ReportTemplet reportT = reportTempletService.getByID(Integer.valueOf(id));
//                        int flag_up = 0;
//                        reportT.setModifyUser(UserCode);
//                        Date day=new Date();
//                        reportT.setModifyTime(day);
//                        flag_up = reportTempletService.updateReportTempletInfo(reportT);
//                    }
                }

            }
        }catch (Exception e) {
            log.error(e.getMessage());
        }
        String status = jsonObj!=null?jsonObj.get("status").toString():"";
        if("3".equals(status)||"7".equals(status)) {//不强制手动保存时为6,"6".equals(status)
            log.debug("====保存失败:");
            writer.write("{\"error\":1}");
        }else {
            log.debug("状态为:0") ;
            writer.write("{\"error\":" + "0" + "}");
        }
    }


    public RestResult<Object> operationCheck(String token){
        RestResult<Object> result = new RestResult<Object>();
        UserBean sessionUserBean = userService.getUserBeanByToken(token);
        if (sessionUserBean == null){
            result.setSuccess(false);
            result.setMessage("未登录");
            return result;
        }
        if (qiwenFileConfig.isShareMode()){
            if (sessionUserBean.getUserId() > 2){
                result.setSuccess(false);
                result.setMessage("没权限,请联系管理员!");
                return result;
            }
        }
        result.setSuccess(true);
        return result;
    }
}
EditorConfig配置类:
package com.qiwenshare.file.domain;
import com.alibaba.fastjson.JSON;
import com.qiwenshare.file.dto.file.OnlyofficeDTO;
import com.qiwenshare.file.util.DocumentManager;
import com.qiwenshare.file.util.FileUtility;
import com.qiwenshare.file.util.ServiceConverter;
import io.netty.util.internal.StringUtil;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class OnlyofficeFileModel
{
    public String type = "desktop";
    public String documentType;
    public Document document;
    public EditorConfig editorConfig;
    public String token;

    public OnlyofficeFileModel(UserBean loginUser, OnlyofficeDTO onlyofficeDTO, String mode) {
        String type = onlyofficeDTO.getType();
        String fileId = onlyofficeDTO.getFileId();
        String fileName = onlyofficeDTO.getFileName();
        String filePath = onlyofficeDTO.getFilePath();
        String fileUrl = onlyofficeDTO.getFileUrl();
        if (fileName == null) {
            fileName = "";
        }
        fileName = fileName.trim();
        documentType = FileUtility.GetFileType(fileName).toString().toLowerCase();
        document = new Document();
        document.title = fileName;
//        String suffix = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
//        System.out.println(suffix);
        document.fileType = FileUtility.GetFileExtension(fileUrl).replace(".", "");
        document.url = fileUrl;
        editorConfig = new EditorConfig();
        editorConfig.mode = mode;
        editorConfig.callbackUrl = "";
        editorConfig.user.id = String.valueOf(loginUser.getUserId());
        editorConfig.user.name = loginUser.getUsername();
        String userId = DocumentManager.CurUserHostAddress(null);
        document.key = ServiceConverter.GenerateRevisionId(userId + "/" + fileName);
    }

    public void InitDesktop()
    {
        type = "embedded";
        editorConfig.InitDesktop(document.url);
    }

    public void BuildToken()
    {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("documentType", documentType);
        map.put("document", document);
        map.put("editorConfig", editorConfig);

        token = DocumentManager.CreateToken(map);
    }

    public class Document
    {
        public String title;
        public String url;
        public String fileType;
        public String key;
    }

    public class EditorConfig
    {
        public String mode = "edit";
        public String callbackUrl;
        public User user;
        public Customization customization;
        public Embedded embedded;
        public String lang ="zh-CN";
        public Plugins plugins;

        public EditorConfig()
        {
            user = new User();
            customization = new Customization();
            plugins = new Plugins();
            String[] autostart = {"asc.{7327FC95-16DA-41D9-9AF2-0E7F449F687D}"};
            plugins.autostart = autostart;
        }

        public void InitDesktop(String url)
        {
            embedded = new Embedded();
            embedded.saveUrl = url;
            embedded.embedUrl = url;
            embedded.shareUrl = url;
            embedded.toolbarDocked = "top";
        }

        public class User
        {
            public String id;
            public String name = " ";//Administrator
        }

        public class Customization
        {
            public Goback goback;
            public boolean forcesave = true;//是否启动强制保存
            public boolean autosave = false;//是否启动自动保存
            public boolean spellcheck = true;//关闭拼写检查
            public Customization()
            {
                goback = new Goback();
            }

            public class Goback
            {
                public String url;
            }
        }

        public class Embedded
        {
            public String saveUrl;
            public String embedUrl;
            public String shareUrl;
            public String toolbarDocked;
        }
    }


    public static String Serialize(OnlyofficeFileModel model)
    {
        return JSON.toJSONString(model);
    }

    public class Plugins
    {
        public String[] pluginsData;
        public String[] autostart;
    }
}
参考官网demo的工具类:

ConfigManager.java

/*
 *
 * (c) Copyright Ascensio System SIA 2019
 *
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
*/


package com.qiwenshare.file.util;

import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Properties;
@Component
public class ConfigManager
{
    private static Properties properties;

    static
    {
        Init();
    }

    private static void Init()
    {
        try
        {
            properties = new Properties();
            InputStream stream = ConfigManager.class.getResourceAsStream("/config/settings.properties");
//            InputStream stream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream("/config/settings.properties");
            properties.load(stream);
        }
        catch (Exception ex)
        {
            properties = null;
        }
    }

    public static String GetProperty(String name)
    {
        if (properties == null)
        {
            return "";
        }

        String property = properties.getProperty(name);

        return property == null ? "" : property;
    }
}

FileUtility.java

/*
 *
 * (c) Copyright Ascensio System SIA 2019
 *
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
*/


package com.qiwenshare.file.util;

import com.qiwenshare.file.domain.FileType;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtility
{
    static {}

    public static FileType GetFileType(String fileName)
    {
        String ext = GetFileExtension(fileName).toLowerCase();

        if (ExtsDocument.contains(ext))
            return FileType.Text;

        if (ExtsSpreadsheet.contains(ext))
            return FileType.Spreadsheet;

        if (ExtsPresentation.contains(ext))
            return FileType.Presentation;

        return FileType.Text;
    }

    public static List<String> ExtsDocument = Arrays.asList
            (
                    ".doc", ".docx", ".docm",
                    ".dot", ".dotx", ".dotm",
                    ".odt", ".fodt", ".ott", ".rtf", ".txt",
                    ".html", ".htm", ".mht",
                    ".pdf", ".djvu", ".fb2", ".epub", ".xps"
            );

    public static List<String> ExtsSpreadsheet = Arrays.asList
            (
                    ".xls", ".xlsx", ".xlsm",
                    ".xlt", ".xltx", ".xltm",
                    ".ods", ".fods", ".ots", ".csv"
            );

    public static List<String> ExtsPresentation = Arrays.asList
            (
                    ".pps", ".ppsx", ".ppsm",
                    ".ppt", ".pptx", ".pptm",
                    ".pot", ".potx", ".potm",
                    ".odp", ".fodp", ".otp"
            );


    public static String GetFileName(String url)
    {
        if (url == null) return null;

        //for external file url
        String tempstorage = ConfigManager.GetProperty("files.docservice.url.tempstorage");
        if (!tempstorage.isEmpty() && url.startsWith(tempstorage))
        {
            Map<String, String> params = GetUrlParams(url);
            return params == null ? null : params.get("filename");
        }

        String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
        return fileName;
    }

    public static String GetFileNameWithoutExtension(String url)
    {
        String fileName = GetFileName(url);
        if (fileName == null) return null;
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));
        return fileNameWithoutExt;
    }

    public static String GetFileExtension(String url)
    {
        String fileName = GetFileName(url);
        if (fileName == null) return null;
        String fileExt = fileName.substring(fileName.lastIndexOf("."));
        return fileExt.toLowerCase();
    }

    public static Map<String, String> GetUrlParams(String url)
    {
        try
        {
            String query = new URL(url).getQuery();
            String[] params = query.split("&");
            Map<String, String> map = new HashMap<>();
            for (String param : params)
            {
                String name = param.split("=")[0];
                String value = param.split("=")[1];
                map.put(name, value);
            }
            return map;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}

DocumentManager.java

/*
 *
 * (c) Copyright Ascensio System SIA 2019
 *
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
*/

package com.qiwenshare.file.util;

import com.google.gson.Gson;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class ServiceConverter
{
    private static int ConvertTimeout = 120000;
    private static final String DocumentConverterUrl = ConfigManager.GetProperty("files.docservice.url.converter");
    private static final String DocumentJwtHeader = ConfigManager.GetProperty("files.docservice.header");

    public static class ConvertBody
    {
        public String url;
        public String outputtype;
        public String filetype;
        public String title;
        public String key;
        public Boolean async;
        public String token;
    }

    static
    {
        try
        {
            int timeout = Integer.parseInt(ConfigManager.GetProperty("files.docservice.timeout"));
            if (timeout > 0) 
            {
                ConvertTimeout = timeout;
            }
        }
        catch (Exception ex)
        {
        }
    }

    public static String GetConvertedUri(String documentUri, String fromExtension, String toExtension, String documentRevisionId, Boolean isAsync) throws Exception
    {
        fromExtension = fromExtension == null || fromExtension.isEmpty() ? FileUtility.GetFileExtension(documentUri) : fromExtension;

        String title = FileUtility.GetFileName(documentUri);
        title = title == null || title.isEmpty() ? UUID.randomUUID().toString() : title;

        documentRevisionId = documentRevisionId == null || documentRevisionId.isEmpty() ? documentUri : documentRevisionId;

        documentRevisionId = GenerateRevisionId(documentRevisionId);

        ConvertBody body = new ConvertBody();
        body.url = documentUri;
        body.outputtype = toExtension.replace(".", "");
        body.filetype = fromExtension.replace(".", "");
        body.title = title;
        body.key = documentRevisionId;
        if (isAsync)
            body.async = true;

        String headerToken = "";
        if (DocumentManager.TokenEnabled())
        {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("url", body.url);
            map.put("outputtype", body.outputtype);
            map.put("filetype", body.filetype);
            map.put("title", body.title);
            map.put("key", body.key);
            if (isAsync)
                map.put("async", body.async);

            String token = DocumentManager.CreateToken(map);
            body.token = token;

            Map<String, Object> payloadMap = new HashMap<String, Object>();
            payloadMap.put("payload", map);
            headerToken = DocumentManager.CreateToken(payloadMap);
        }

        Gson gson = new Gson();
        String bodyString = gson.toJson(body);

        byte[] bodyByte = bodyString.getBytes(StandardCharsets.UTF_8);

        URL url = new URL(DocumentConverterUrl);
        java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setFixedLengthStreamingMode(bodyByte.length);
        connection.setRequestProperty("Accept", "application/json");
        connection.setConnectTimeout(ConvertTimeout);

        if (DocumentManager.TokenEnabled())
        {
            connection.setRequestProperty(DocumentJwtHeader == "" ? "Authorization" : DocumentJwtHeader, "Bearer " + headerToken);
        }

        connection.connect();
        try (OutputStream os = connection.getOutputStream()) {
            os.write(bodyByte);
        }

        InputStream stream = connection.getInputStream();

        if (stream == null)
            throw new Exception("Could not get an answer");

        String jsonString = ConvertStreamToString(stream);

        connection.disconnect();

        return GetResponseUri(jsonString);
    }

    public static String GenerateRevisionId(String expectedKey)
    {
        if (expectedKey.length() > 20)
            expectedKey = Integer.toString(expectedKey.hashCode());

        String key = expectedKey.replace("[^0-9-.a-zA-Z_=]", "_");

        return key.substring(0, Math.min(key.length(), 20));
    }

    private static void ProcessConvertServiceResponceError(int errorCode) throws Exception
    {
        String errorMessage = "";
        String errorMessageTemplate = "Error occurred in the ConvertService: ";

        switch (errorCode)
        {
            case -8:
                errorMessage = errorMessageTemplate + "Error document VKey";
                break;
            case -7:
                errorMessage = errorMessageTemplate + "Error document request";
                break;
            case -6:
                errorMessage = errorMessageTemplate + "Error database";
                break;
            case -5:
                errorMessage = errorMessageTemplate + "Error unexpected guid";
                break;
            case -4:
                errorMessage = errorMessageTemplate + "Error download error";
                break;
            case -3:
                errorMessage = errorMessageTemplate + "Error convertation error";
                break;
            case -2:
                errorMessage = errorMessageTemplate + "Error convertation timeout";
                break;
            case -1:
                errorMessage = errorMessageTemplate + "Error convertation unknown";
                break;
            case 0:
                break;
            default:
                errorMessage = "ErrorCode = " + errorCode;
                break;
        }

        throw new Exception(errorMessage);
    }

    private static String GetResponseUri(String jsonString) throws Exception
    {
        JSONObject jsonObj = ConvertStringToJSON(jsonString);

        Object error = jsonObj.get("error");
        if (error != null)
            ProcessConvertServiceResponceError(Math.toIntExact((long)error));

        Boolean isEndConvert = (Boolean) jsonObj.get("endConvert");

        Long resultPercent = 0l;
        String responseUri = null;

        if (isEndConvert)
        {
            resultPercent = 100l;
            responseUri = (String) jsonObj.get("fileUrl");
        }
        else
        {
            resultPercent = (Long) jsonObj.get("percent");
            resultPercent = resultPercent >= 100l ? 99l : resultPercent;
        }

        return resultPercent >= 100l ? responseUri : "";
    }

    private static String ConvertStreamToString(InputStream stream) throws IOException
    {
        InputStreamReader inputStreamReader = new InputStreamReader(stream);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line = bufferedReader.readLine();

        while (line != null)
        {
            stringBuilder.append(line);
            line = bufferedReader.readLine();
        }

        String result = stringBuilder.toString();

        return result;
    }

    private static JSONObject ConvertStringToJSON(String jsonString) throws ParseException
    {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(jsonString);
        JSONObject jsonObj = (JSONObject) obj;

        return jsonObj;
    }
}
/*
 *
 * (c) Copyright Ascensio System SIA 2019
 *
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
*/

package com.qiwenshare.file.util;

import com.qiwenshare.file.domain.FileType;
import org.primeframework.jwt.Signer;
import org.primeframework.jwt.Verifier;
import org.primeframework.jwt.domain.JWT;
import org.primeframework.jwt.hmac.HMACSigner;
import org.primeframework.jwt.hmac.HMACVerifier;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class DocumentManager
{
    private static HttpServletRequest request;

    public static void Init(HttpServletRequest req, HttpServletResponse resp)
    {
        request = req;
    }

    public static long GetMaxFileSize()
    {
        long size;

        try
        {
            size = Long.parseLong(ConfigManager.GetProperty("filesize-max"));
        }
        catch (Exception ex)
        {
            size = 0;
        }

        return size > 0 ? size : 5 * 1024 * 1024;
    }

    public static List<String> GetFileExts()
    {
        List<String> res = new ArrayList<>();

        res.addAll(GetViewedExts());
        res.addAll(GetEditedExts());
        res.addAll(GetConvertExts());

        return res;
    }

    public static List<String> GetViewedExts()
    {
        String exts = ConfigManager.GetProperty("files.docservice.viewed-docs");
        return Arrays.asList(exts.split("\\|"));
    }

    public static List<String> GetEditedExts()
    {
        String exts = ConfigManager.GetProperty("files.docservice.edited-docs");
        return Arrays.asList(exts.split("\\|"));
    }

    public static List<String> GetConvertExts()
    {
        String exts = ConfigManager.GetProperty("files.docservice.convert-docs");
        return Arrays.asList(exts.split("\\|"));
    }

    public static String CurUserHostAddress(String userAddress)
    {
        if(userAddress == null)
        {
            try
            {
                userAddress = InetAddress.getLocalHost().getHostAddress();
            }
            catch (Exception ex)
            {
                userAddress = "";
            }
        }

        return userAddress.replaceAll("[^0-9a-zA-Z.=]", "_");
    }

    public static String StoragePath(String fileName, String userAddress)
    {
        String serverPath = request.getSession().getServletContext().getRealPath("");
        String storagePath = ConfigManager.GetProperty("storage-folder");
        String hostAddress = CurUserHostAddress(userAddress);
        String directory = serverPath + File.separator + storagePath + File.separator;

        File file = new File(directory);

        if (!file.exists())
        {
            file.mkdir();
        }

        directory = directory + hostAddress + File.separator;
        file = new File(directory);

        if (!file.exists())
        {
            file.mkdir();
        }

        return directory + fileName;
    }

    public static String GetCorrectName(String fileName)
    {
        String baseName = FileUtility.GetFileNameWithoutExtension(fileName);
        String ext = FileUtility.GetFileExtension(fileName);
        String name = baseName + ext;

        File file = new File(StoragePath(name, null));

        for (int i = 1; file.exists(); i++)
        {
            name = baseName + " (" + i + ")" + ext;
            file = new File(StoragePath(name, null));
        }

        return name;
    }

    public static String CreateDemo(String fileExt) throws Exception
    {
        String demoName = "sample." + fileExt;
        String fileName = GetCorrectName(demoName);

        InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(demoName);

        File file = new File(StoragePath(fileName, null));

        try (FileOutputStream out = new FileOutputStream(file))
        {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = stream.read(bytes)) != -1)
            {
                out.write(bytes, 0, read);
            }
            out.flush();
        }

        return fileName;
    }

    public static String GetFileUri(String fileName)
    {
        try
        {
            String serverPath = GetServerUrl();
            String storagePath = ConfigManager.GetProperty("storage-folder");
            String hostAddress = CurUserHostAddress(null);

            String filePath = serverPath + "/" + storagePath + "/" + hostAddress + "/" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()).replace("+", "%20");

            return filePath;
        }
        catch (UnsupportedEncodingException e)
        {
            return "";
        }
    }

    public static String GetServerUrl()
    {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    public static String GetCallback(String fileName)
    {
        String serverPath = GetServerUrl();
        String hostAddress = CurUserHostAddress(null);
        try
        {
            String query = "?type=track&fileName=" + URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.toString()) + "&userAddress=" + URLEncoder.encode(hostAddress, java.nio.charset.StandardCharsets.UTF_8.toString());

            return serverPath + "/IndexServlet" + query;
        }
        catch (UnsupportedEncodingException e)
        {
            return "";
        }
    }

    public static String GetInternalExtension(FileType fileType)
    {
        if (fileType.equals(FileType.Text))
            return ".docx";

        if (fileType.equals(FileType.Spreadsheet))
            return ".xlsx";

        if (fileType.equals(FileType.Presentation))
            return ".pptx";

        return ".docx";
    }

    public static String CreateToken(Map<String, Object> payloadClaims)
    {
        try
        {
            Signer signer = HMACSigner.newSHA256Signer(GetTokenSecret());
            JWT jwt = new JWT();
            for (String key : payloadClaims.keySet())
            {
                jwt.addClaim(key, payloadClaims.get(key));
            }
            return JWT.getEncoder().encode(jwt, signer);
        }
        catch (Exception e)
        {
            return "";
        }
    }

    public static JWT ReadToken(String token)
    {
        try
        {
            Verifier verifier = HMACVerifier.newVerifier(GetTokenSecret());
            return JWT.getDecoder().decode(token, verifier);
        }
        catch (Exception exception)
        {
            return null;
        }
    }

    public static Boolean TokenEnabled()
    {
        String secret = GetTokenSecret();
        return secret != null && !secret.isEmpty();
    }

    private static String GetTokenSecret()
    {
        return ConfigManager.GetProperty("files.docservice.secret");
    }
}

FileType.java

/*
 *
 * (c) Copyright Ascensio System SIA 2019
 *
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
*/


package com.qiwenshare.file.domain;

public enum FileType
{
    Text,
    Spreadsheet,
    Presentation
}

前端代码:

Onlyoffice.vue

<!--
 * @Description: 报告onlyoffice组件
 * @Author: chenfengtao
 * @Date: 2020-02-18 10:46:52
 * @LastEditors: chenfengtao
 * @LastEditTime: 2020-02-18 10:46:52
 -->
<template>
<div class="report-onlyoffice">
  <div id="placeholder"></div>
</div>
</template>

<script>
import { createReportForOnlyofficeApi, editReportForOnlyofficeApi, showReportForOnlyofficeApi } from '@/request/onlyoffice.js'
export default {
  name: 'report-onlyoffice',
  data () {
    return {
      fileInfo: {
        userFileId: '',
        fileId: '',
        fileName: '',
        fileUrl: '',
        filePath: ''
      },
      docEditor: null,
      platform: 'desktop'
    }
  },
  created () {
    this.judgePlatform()
  },
  mounted () {
    this.$nextTick(() => {
      debugger
      let ot = this.$route.query.ot
      this.fileInfo.fileUrl = this.$route.query.fileUrl
      this.fileInfo.fileName = this.$route.query.fileName
      this.fileInfo.filePath = this.$route.query.filePath
      this.fileInfo.fileId = this.$route.query.fileId
      this.fileInfo.userFileId = this.$route.query.userFileId
      // 添加
      if (ot === 'add') {
        this.initOnlyoffice()
      } else if (ot === 'edit') {
        this.editDoc()
      } else if (ot === 'detail') {
        this.showDocDetail()
      }
    })
  },
  methods: {
    initOnlyoffice,
    initDocEditor,
    judgePlatform,
    showDocDetail,
    editDoc,
    loadOnlyOfficeAPI
  },
  destroyed () {
    this.docEditor.destroyEditor()
  }
}

function initOnlyoffice () {
  let data = {
    userFileId: this.fileInfo.userFileId,
    fileId: this.fileInfo.fileId,
    fileName: this.fileInfo.fileName,
    filePath: this.fileInfo.filePath,
    fileCategory: this.fileInfo.fileCategory,
    type: this.fileInfo.type,
    memo: this.fileInfo.memo
  }

  createReportForOnlyofficeApi(data).then(resp => {
    if (resp.code === 200) {
      var config = resp.data.file
      config.type = this.platform
      // config.editorConfig.callbackUrl = config.editorConfig.callbackUrl.replace('/IndexServlet', ONLYOFFICE_BASE_URL + '/IndexServlet')
      // console.log(BASE_URL)
      // console.log(config.editorConfig.callbackUrl)
      let { docserviceApiUrl } = resp.data

      this.initDocEditor(docserviceApiUrl, config)
    }
  })
}

function initDocEditor (docserviceApiUrl, config) {
  this.loadOnlyOfficeAPI(docserviceApiUrl).then(() => {
    /* global DocsAPI */
    this.docEditor = new DocsAPI.DocEditor('placeholder', config)
  })
}

function judgePlatform () {
  var platform = 'desktop'// 浏览平台
  if (/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))) {
    if (window.location.href.indexOf('?mobile') < 0) {
      try {
        if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
          platform = 'mobile'
        }
      } catch (e) {}
    }
  }
  this.platform = platform
}

function showDocDetail () {
  let fileUrl = this.fileInfo.fileUrl
  let fileName = this.fileInfo.fileName

  let data = {
    fileUrl: fileUrl,
    fileName: fileName
  }
  debugger
  showReportForOnlyofficeApi(data).then(resp => {
    if (resp.code === 200) {
      var config = resp.data.file
      config.type = this.platform
      let { docserviceApiUrl } = resp.data
      // http://10.170.128.54:9000/web-apps/apps/api/documents/api.js
      this.initDocEditor(docserviceApiUrl, config)
    }
  })
}
function editDoc () {
  let data = {
    userFileId: this.fileInfo.userFileId,
    fileId: this.fileInfo.fileId,
    fileName: this.fileInfo.fileName,
    filePath: this.fileInfo.filePath,
    fileUrl: this.fileInfo.fileUrl
  }
  editReportForOnlyofficeApi(data).then(resp => {
    if (resp.code === 200) {
      var config = resp.data.file
      config.type = this.platform
      let { docserviceApiUrl } = resp.data
      this.initDocEditor(docserviceApiUrl, config)
    }
  })
}

function loadOnlyOfficeAPI (src) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = src
    document.body.appendChild(script)
    script. () => {
      resolve()
    }
    /* script.onerror = () => {
      reject()
    } */
  })
}
</script>

<style lang="stylus" scoped>
.report-onlyoffice {
  height: 100%;
  width: 100%;
}
#app .mainContent {
  height: 100%;
  width: 100%;
}
</style>

onlyoffice.js

// 用户信息相关接口
import { get, post } from './http'

/**
 * 以登录接口为例 
 * export const login = p => get('/user/login', p);
 * 
 * login ---------- 接口名称
 * p -------------- 传参,若需要在url中拼接其他信息,传参可以改为(p, other)
 * get ------------ 接口调用的方法,来自 http.js 中封装好的四个axios方法 get/post/put/axiosDelete
 * '/user/login' -- 接口url,若需要在url中拼接其他信息:
 *                  首先需要在传参处改为(p, other1, other2)
 *                  然后将url改为`/user/${other1}/login/${other2}`
 * p -------------- 传递给 get/post/put/axiosDelete 中的查询参数/请求体
 * 
 * 
 * 
 * 除此之外,POST 请求支持请求体格式为 FormData,那么就需要多传递一个参数,true,如下示例:
 * export const example = p => post('/test/example', p, true);
 */

// 创建报告
export const createReportForOnlyofficeApi = p => post('/office/createReportForOnlyofficeApi', p);
// 编辑报告
export const editReportForOnlyofficeApi = p => post('/office/editReportForOnlyofficeApi', p);
// 查看报告
export const showReportForOnlyofficeApi = p => post('/office/showReportForOnlyofficeApi', p);

globalFunction.js

import Cookies from 'js-cookie'
import config from '@/config'
import { Message } from 'element-ui';

// 全局函数
const globalFunction = {
  /**
   * 格式化文件大小
   * @param {number} size 文件大小
   * @returns {string} 文件大小(带单位)
   */
  calculateFileSize: function (size) {
    const B = 1024
    const KB = Math.pow(1024, 2)
    const MB = Math.pow(1024, 3)
    const GB = Math.pow(1024, 4)
    if (!size) {
      return '_'
    } else if (size < KB) {
      return (size / B).toFixed(0) + 'KB'
    } else if (size < MB) {
      return (size / KB).toFixed(1) + 'MB'
    } else if (size < GB) {
      return (size / MB).toFixed(2) + 'GB'
    } else {
      return (size / GB).toFixed(3) + 'TB'
    }
  },
  /**
   * 获取图片缩略图路径
   * @param {object} row 文件信息
   * @returns {string} 图片缩略图路径
   */
  getImgMinPath: function (row) {
    let fileUrl = ''
    if (row.fileUrl) {
      if (row.isOSS == 1) {
        // 阿里云OSS对象存储
        fileUrl = `https://${Cookies.get('viewDomain')}${row.fileUrl}?x-oss-process=image/resize,m_fill,h_150,w_150/rotate,0`
      } else {
        // 本地磁盘存储
        let index = row.fileUrl.lastIndexOf('.')
        fileUrl = '/api' + row.fileUrl.substr(0, index) + '_min' + row.fileUrl.substr(index)
      }
    }
    return fileUrl
  },
  /**
   * 获取文件查看路径
   * @param {object} row 文件信息
   * @returns {string} 文件路径
   */
  getViewFilePath: function (row) {
    return `/api/filetransfer/preview?userFileId=${row.userFileId}`
  },
  /**
   * 获取文件下载路径
   * @param {object} row 文件信息
   * @returns {string}  文件下载路径
   */
  getDownloadFilePath: function (row) {
    return `/api/filetransfer/downloadfile?userFileId=${row.userFileId}`
  },
  /**
   * 获取 Onlyoffice 文件创建路径
   * @param {object} row 
   * @returns {string} office 文件创建路径
   */
   createFileOnlineByOffice: function (data) {
    debugger
    // 本地磁盘存储 - 在本地开发环境中,本地磁盘存储的文件是无法预览的,因为 office 要求文件可以在 Internet 访问
    let fileUrl = `${location.protocol}//${location.host}/api`
    debugger
    const { href } = this.$router.resolve({
      path: 'onlyoffice',
      query: {
        fileUrl: fileUrl,
        fileName: data.fileName,
        filePath: data.filePath,
        extendName: data.extendName,
        ot: 'add'
      }
    })
    window.open(href, '_blank')
  },
  /**
   * 获取 Onlyoffice 文件在线预览路径
   * @param {object} row 
   * @returns {string} office 文件在线预览路径
   */
   getFileOnlineViewPathByOffice: function (row) {
    debugger
    let fileUrl = ''
    let fileName = row.fileName + "." + row.extendName
    let filePath = row.fileUrl
    let fileId = row.fileId
    let userFileId = row.userFileId
    if (row.isOSS == 1) {
      fileUrl = `https://${Cookies.get('viewDomain')}${row.fileUrl}`  // 阿里云OSS对象存储
    } else {
      // 本地磁盘存储 - 在本地开发环境中,本地磁盘存储的文件是无法预览的,因为 office 要求文件可以在 Internet 访问
      fileUrl = `${location.protocol}//${location.host}/api${row.fileUrl}`
    }
    debugger
    const { href } = this.$router.resolve({
      path: 'onlyoffice',
      query: {
        fileUrl: fileUrl,
        fileName: fileName,
        filePath: filePath,
        fileId: fileId,
        userFileId: userFileId,
        ot: 'detail'
      }
    })
    window.open(href, '_blank')
  },
  /**
   * 获取 Onlyoffice 文件在线编辑路径
   * @param {object} row 
   * @returns {string} office 文件在线编辑路径
   */
   getFileOnlineEditPathByOffice: function (row) {
    let fileUrl = ''
    let fileName = row.fileName + "." + row.extendName
    let filePath = row.fileUrl
    let fileId = row.fileId
    let userFileId = row.userFileId
    if (row.isOSS == 1) {
      fileUrl = `https://${Cookies.get('viewDomain')}${row.fileUrl}`  // 阿里云OSS对象存储
    } else {
      // 本地磁盘存储 - 在本地开发环境中,本地磁盘存储的文件是无法编辑的,因为 office 要求文件可以在 Internet 访问
      fileUrl = `${location.protocol}//${location.host}/api${row.fileUrl}`
    }
    debugger
    const { href } = this.$router.resolve({
      path: 'onlyoffice',
      query: {
        fileUrl: fileUrl,
        fileName: fileName,
        filePath: filePath,
        fileId: fileId,
        userFileId: userFileId,
        ot: 'edit'
      }
    })
    window.open(href, '_blank')
  },
  /**
   * 获取 office 文件在线预览路径
   * @param {object} row 
   * @returns {string} office 文件在线预览路径
   */
  getFileOnlineViewPathByOffice2: function (row) {
    let fileUrl = ''
    if (row.isOSS == 1) {
      fileUrl = `https://${Cookies.get('viewDomain')}${row.fileUrl}`  // 阿里云OSS对象存储
    } else {
      // 本地磁盘存储 - 在本地开发环境中,本地磁盘存储的文件是无法预览的,因为 office 要求文件可以在 Internet 访问
      fileUrl = `${location.protocol}//${location.host}/api${row.fileUrl}`
    }
    debugger
    return `https://view.officeapps.live.com/op/embed.aspx?src=${fileUrl}`
  },
  /**
   * 设置 Cookies
   * @param {string} name 名称
   * @param {string} value 值
   * @param {object} others 域名、路径、有效期等,封装到对象中
   */
  setCookies: function (name, value, others = null) {
    Cookies.set(name, value, { domain: config.domain, ...others })
  },
  /**
   * 获取 Cookies
   * @param {string} name 名称
   * @param {object} others 域名、路径等,封装到对象中
   * @returns {string} Cookies 值
   */
  getCookies: function (name, others = null) {
    return Cookies.get(name, { domain: config.domain, ...others })
  },
  /**
   * 移除 Cookies
   * @param {string} name 名称
   * @param {object} others 域名、路径等,封装到对象中
   */
  removeCookies: function (name, others = null) {
    Cookies.remove(name, { domain: config.domain, ...others })
  },
  /**
   * 获取分享链接
   * @param {string} shareBatchNum 
   * @returns {string} 完整的分享链接
   */
  getShareLink: function (shareBatchNum) {
    return `${location.protocol}//${location.host}/share/${shareBatchNum}`
  },
  /**
   * 复制分享链接
   * @param {string} shareBatchNum 
   * @param {string} extractionCode 
   */
  copyShareLink: function (shareBatchNum, extractionCode) {
    let input = document.createElement('textarea') // 直接构建textarea以保持换行
    input.value =
      extractionCode === null
        ? `分享链接:${this.getShareLink(
          shareBatchNum
        )}\n复制链接到浏览器中并输入提取码即可查看文件`
        : `分享链接:${this.getShareLink(shareBatchNum)}\n提取码:${extractionCode
        }\n复制链接到浏览器中并输入提取码即可查看文件` // 设置内容
    document.body.appendChild(input) // 添加临时实例
    input.select() // 选择实例内容
    document.execCommand('Copy') // 执行复制
    document.body.removeChild(input) // 删除临时实例
    Message.success('复制成功')
  }
}

export default globalFunction

整体代码可以在下面附件中获取:附件注册登录签到领1积分可获取。↓↓↓↓

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: