1、环境搭建:暂略
2、代码
后端
onlyoffice协同办公后端:
实体类:
文件表实体类:
public class File implements Serializable{
private static final long serialVersionUID = 1L;
private String fileId;
private String fileName;
private String crateTime;
private String updateTime;
private String createBy;
private String updateBy;
private String isDel;
}
历史记录表实体类:
public class FileHistoryLog extends BaseEntity{
private static final long serialVersionUID = 1L;
private String historyFileId;
private String fileId;
private String lastSave; //最后保存事件
private String notmodified; //最后不修改
private String changesUrl;//修改记录zip包路径
private String serverVersion; //服务器版本
private String changes; //用户修改记录json数组
private String actions;//共同编辑用户json数组
private String key; //当前版本号
private String url; //当前最新记录
private String users; //用户数组字符串
private String stauts;
private String realUrl; //最新版本文件下载路径
private String isDel;
private String previousKey; //之前版本的key
private String previousUrl; //之前版本的url
}
onlyoffice的通用请求处理
@RestController
@RequestMapping("/onlyoffice/data")
public class OnlyOfficeDataController{
private final OnlyOfficeUserDocumentService cods;
private final TokenService tokenService;
@Autowired
public OblyOfficeDataController(OnlyOfficeUserDocumentService cods,TokenService tokenService){
this.cods = code;
this.tokenService= tokenService;
}
//根据文件id和当前登录用户,查询用户是否具有权限编辑,并返回文件相关信息
@GetMapping("/selectFileInfoByFileId")
public Response<File> selectFileInfoByFileId(@ModelAttribute File data,HttpServletRequest request){
LoginUser user = tokenSerivce.getLoginUser(request);
data.setUserId(user.getUser.getUserId());
if(StringUtils.isEmpty(data.getFileId()){
//前端传递过来的文件id为空
return Response.error(ResponseEnum.ONLY_OFFICE_FILEID_FAIL);
}
File file = cods.selectFileInfoByFileId(data); //查询前端传递过来的文件id查询文件信息
file.setUserId(user.getUser.getUserId);
file.setNickName(user.getUser.getNickName);
return Response.success(file);
}
}
@RestController
@RequestMapping("/onlyoffice/online")
public class OnlyOfficeOnlineController{
@Autowired
private OnlyOfficeHistoryLogService cohl;
@Autowired
private OnlyOfficeUserDocumentService cods;
@Autowired
private IMcoMeetFileService mcoMeetFileService;
@Autowired
private IMcoOperationHistoryService mcoOpereationHistoryService;
@GetMapping("/getfile")
public void getFile(String fileName,HttpServletResponse response,HttpServletRequest request){
try{
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
FileUtils.writeBytes(ImwConfig.getProfile()+fileName,response.getOutputStream());
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
@RequestMapping("/downloadfile")
public void fileDownloads(HttpServletRequest request,HttpServletResponse response,OFHistoryLog log) throws IOException{
PrintWriter writer = null;
FileOutputStream out = null;
FileOutputStream outz = null;
InputStream stream = null;
InputStream streamz = null;
String realPath = "";
String hisZip = "";
try{
writer = response.getWriter();
Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
String body = scanner.hasNext()?scanner.next():"";
JSONObject jsonObj = JSONObject.parseObject(body);
if((Integer)jsonObj.get("status")==2){
String key = "XT_"+DateUtils.getNowDate().getTime();
String downlaodUri = (String)jsonObj.get("url"); //保存变更后文件
String changeUrl = (String) jsonObj.get("changeurl") //保存文件的修改记录
//文档编辑完成,现在开始保存编辑后的文档,其下载地址为downloadUri
String fileName = request.getParameter("filename");
URL url = new URL(downloadUri);
URL changeUrlZ = new URL(changesUrl);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
java.net.HttpURLConnection connectionz = (java.net.HttpURLConnection)
changeUrlz.openConnection();
stream = connection.getInputStream();
streamz = connectionz.getInputStream();
int s = downloadUri.loatIndexOf(".");
String suff = downloadUri.substring(s,downloadUri.length());
realPath = "onlyoffice/his/"+key +suff;
hisZip = "onlyoffice/his/"+key+".zip";
try{
File savedFile = new File(ImwConfig.getProfile()+realPath);
File zip = new File(ImwConfig.getProfile()+hisZip);
if(!zip.exists()){
File fileparent = new File(zip.getParent());
fileparent.mkdirs();
}
if(!savedFile.exists()){
File fileparent = new File(zip.getParent());
fileparent.mkdirs();
}
out = new FileOutputStream(savedFile);
outz = new FileOutputStream(zip);
int read ;
final byte[] bytes = new byte[1024];
while((read=stream.read(bytes)!=-1)){
out.write(bytes,0,read);
}
out.flush();
int reads;
final byte[] bytesz = new byte[1024];
while((read=streamz.read(bytesz))!=-1){
outz.write(bytesz,0,reads);
}
outz.flush();
connection.disconnect();
//写入完成之后,执行保存数据库逻辑
log.setRealUrl(realPath);
log.setChangesUrl(hisZip);
log.setUrl(realPath);
....
}
}
}catch(IOException e){
e.printStackTrace();
}
writer.write("{\"error\":0}");
}
//通用下载请求
GetMapping("/common/downlaod")
public void fileDownload(String fileName,Boolean delete,HttpServletResponse response,
HttpServletRequest request){
String localPath = ImwConfig.getAvatarPath();
String downloadPath = localPath + StringUtils.substringAfter(filename,Constants.JWT_AVATAR);
try{
String downloadName = StringUtils.substringAfterLast(fileName,"/");
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition","attachment;fileName="+FileUtils.setFileDownloadHeader(request,downlaodName));
FileUtils.writeBytes(fileName,reponse.getOutputStream());
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
前端
//onlyOffice前端
onlyOffice.vue
<template>
<div class="content">
<div id="placeholder" class="nav"></div>
</div>
</template>
<script>
import webpack from "../vue.config";
import {selectFileInfoByFileId} from "@/api/onlyOffice";
export default{
name:"onlyOffice",
data(){
return{
docEditor:"",
userInfo:{},
historyz:[],
onlyOfficeConfig:{},
};
},
created(){
this.$nextTick(()=>{
let ids = ''
let fal = ''
let params = this.$route.query
if(params&¶ms.id){
ids = window.atob(param.id).split('-')[1]
fla = window.atob(param.flag).split('-')[1]
}else{
ids = localStorge.getItem('id')
fla = localStorge.getItem('will')
}
let dataz = {
Id:ids,
will:fla
};
//调用接口查询文件历史版本数据,查询用户是否拥有这个文档,鉴权返回数据操作
selectFileInfoByFileId(dataz).then(response=>{
if(response.code==200){
let data = response.data;
let edit = false;
if(dataz.will=='t'){
edit = true;
}
let s =(data.path).lastIndexOf('.')
let reaType = (data.path).substring(s+1)
this.onlyOfficeConfig['realType'] = realType
this.onlyOfficeConfig['fileType'] = data.fileType
this.onlyOfficeConfig['edit'] = edit
this.onlyOfficeConfig['userId'] = data.userId
.....
data.listof.map(items=>{
items["user"]={
id:items.users,
name:items.userName
};
items["created"] = item.lastSave;
items.changes = JSON.parse(item.changes);
items.actions = JSON.parse(item.actions);
});
this.historyz = data.listof;
this.baseUrl = webpack.devServlet.proxy[process.env.VUE_APP_BASE_API].target;
this.initOnlyOffice();
}
})
})
},
methods:{
initOnlyOffice(){
if(!this.historyz){
this.onRequestHistory = null;
}
this.docEditor = new DocsAPI.DocEditor("placeholder",{
events:{
onRequestHistoryData:this.onRequestHistoryData,
onRequestHistory:this.onRequestHistory,
onRequestHistoryClose:this.onRequestHistoryClose
},
document:{
fileType:this.onlyOfficeConfig.realType,
key:this.onlyOfficeConfig.key,
desc:this.onlyOfficeConfig.fileTitle,
title:this.onlyOfficeConfig.fileName,
permissions:{
comment:true,
download:true,
edit:this.onlyOfficeConfig.edit,
fillForms:true,
print:true,
review:this.onlyOfficeConfig.edit
}
},
url:this.baseUrl+"/onlyOffice/online/getFile?fileName="+
encodeURI(this.onlyOfficeConfig.path)
documentType:this.onlyOfficeConfig.fileType,
lang:"zh-CN",
location:"",
region:"zh",
width:"96%",
editorConfig:{
callbackUrl:this.baseUrl+"onlyOffice/online/downloadfile?priviousKey="+this.onlyOfficeConfig.key+
"&previousUrl="+
this.onlyOfficeConfig.path+
"&userName="+
this.onlyOfficeConfig.name+
"&meetFileId="+
this.onlyOfficeConfig.meetFIleId+
"&users="+
this.onlyOfficeConfig.userId,
lang:"zh-CN",
user:{
id:this.onlyOfficeCOnfig.userId,
name:this.onlyOfficeCOnfig.name
}
}
})
},
onReqestHistoryData(event){
let version = event.data;
let str = {};
if(this.historyz){
this.historyz.map(item=>{
if(item.version==version){
str["changesUrl"]=
this.baseUrl+
"onlyOffice/online/getFile?fileName="+encodeURI(item.changeUrl);
str["key"] = item.key;
str["url"] = this.baseUrl+"onlyOffice/online/getFile?fileName="
+encodeURI(item.realUrl);
str["previous"]["key"] = item.previousKey;
str["previous"]["url"] = this.baseUrl+
"onlyOffice/online/getFile?fileName="+encodeURI(item.previousUrl);
}
})
this.docEditor.setHistoryData(str)
}
},
onRequestHistory(){
if(this.historyz){
this.docEditor.refreshHistory({
currentVersion:8,
history:this.historyz
})
}
},
onRequestHistoryClose(){
document.location.reload();
},
}
}
</script>