提交 a0b877ff 作者: ZhangJingKun

修改保存 zhangjingkun

上级 2d8d4cb0
package com.zzsn.knowbase.controller; package com.zzsn.knowbase.controller;
import com.zzsn.knowbase.entity.KbAuthorizedUser;
import com.zzsn.knowbase.entity.Knowledge; import com.zzsn.knowbase.entity.Knowledge;
import com.zzsn.knowbase.service.IKnowledgeService; import com.zzsn.knowbase.service.IKnowledgeService;
import com.zzsn.knowbase.service.ILocalFileService; import com.zzsn.knowbase.service.ILocalFileService;
import com.zzsn.knowbase.util.SpringContextUtils;
import com.zzsn.knowbase.vo.Result; import com.zzsn.knowbase.vo.Result;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
...@@ -29,8 +31,6 @@ public class KbFileController { ...@@ -29,8 +31,6 @@ public class KbFileController {
@Autowired @Autowired
private ILocalFileService localFileService; private ILocalFileService localFileService;
@Autowired
private IKnowledgeService knowledgeService;
/** /**
* 下载文档接口 * 下载文档接口
...@@ -71,19 +71,6 @@ public class KbFileController { ...@@ -71,19 +71,6 @@ public class KbFileController {
} }
/**
* 临时保存,保存并审核通过, 保存并审核不通过
* @param request
* @param knowledge
* @return
*/
@PostMapping(value = "/editKnowledge")
public Result<?> editKnowledge(HttpServletRequest request, Knowledge knowledge) {
//knowledgeService.addKnowledge();
return null;
}
} }
package com.zzsn.knowbase.controller;
import com.zzsn.knowbase.entity.KbAuthorizedUser;
import com.zzsn.knowbase.entity.KnowFile;
import com.zzsn.knowbase.entity.Knowledge;
import com.zzsn.knowbase.service.ILocalFileService;
import com.zzsn.knowbase.util.SpringContextUtils;
import com.zzsn.knowbase.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* @Version 1.0
* @Author: ZhangJingKun
* @Date: 2024/1/16 15:30
* @Content:
*/
@RestController
@RequestMapping("/api/editKnowledge")
public class KbFileEditKnowledgeController {
@Autowired
private ILocalFileService localFileService;
/**
* 临时保存,保存并审核通过, 保存并审核不通过
* @param request
* @param knowledge
* @return
*
* http://192.168.1.216:80/coauthoring/CommandService.ashx
*/
@PostMapping("/editKnowledge")
public Result<?> editKnowledge(@RequestBody Knowledge knowledge) {
Result result = localFileService.editKnowledge(knowledge);
return result;
}
}
package com.zzsn.knowbase.service; package com.zzsn.knowbase.service;
import com.zzsn.knowbase.entity.KnowFile; import com.zzsn.knowbase.entity.KnowFile;
import com.zzsn.knowbase.entity.Knowledge;
import com.zzsn.knowbase.vo.Result; import com.zzsn.knowbase.vo.Result;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
...@@ -63,6 +64,7 @@ public interface ILocalFileService { ...@@ -63,6 +64,7 @@ public interface ILocalFileService {
void callBack(HttpServletRequest request, HttpServletResponse response) throws IOException; void callBack(HttpServletRequest request, HttpServletResponse response) throws IOException;
Result<?> editKnowledge(Knowledge knowledge);
} }
...@@ -75,9 +75,6 @@ class KnowledgeServiceImpl implements IKnowledgeService { ...@@ -75,9 +75,6 @@ class KnowledgeServiceImpl implements IKnowledgeService {
@Override @Override
public void addKnowledge(KnowFile knowFile, Knowledge knowledge, KbAuthorizedUser userInfo) { public void addKnowledge(KnowFile knowFile, Knowledge knowledge, KbAuthorizedUser userInfo) {
knowledge.setAuthor(userInfo.getName()); knowledge.setAuthor(userInfo.getName());
if (null == knowledge.getId()) {
knowledge.setId(codeGenerateUtil.geneIdNo(Constants.FINANCE, 8));
}
if (null == knowledge.getVerifyStatus()) { if (null == knowledge.getVerifyStatus()) {
knowledge.setVerifyStatus(0); knowledge.setVerifyStatus(0);
} }
...@@ -135,8 +132,14 @@ class KnowledgeServiceImpl implements IKnowledgeService { ...@@ -135,8 +132,14 @@ class KnowledgeServiceImpl implements IKnowledgeService {
} }
} }
knowledge.setContents(contentList); knowledge.setContents(contentList);
//id为空表示新增
if (null == knowledge.getId()) {
knowledge.setId(codeGenerateUtil.geneIdNo(Constants.FINANCE, 8));
esOpUtil.docSavaByEntity(Constants.ES_DATA_FOR_KNOWLEDGE, knowledge.getId(), knowledge); esOpUtil.docSavaByEntity(Constants.ES_DATA_FOR_KNOWLEDGE, knowledge.getId(), knowledge);
} else {
//id不为空表示修改数据
esOpUtil.docEditByEntity(Constants.ES_DATA_FOR_KNOWLEDGE, knowledge.getId(), knowledge);
}
//删除 //删除
deleteForPython(knowledge.getId()); deleteForPython(knowledge.getId());
KnowledgeMessage knowledgeMessage = new KnowledgeMessage(); KnowledgeMessage knowledgeMessage = new KnowledgeMessage();
......
package com.zzsn.knowbase.service.impl; package com.zzsn.knowbase.service.impl;
import com.alibaba.fastjson.JSON;
import com.zzsn.knowbase.constant.Constants; import com.zzsn.knowbase.constant.Constants;
import com.zzsn.knowbase.constant.DocumentConstants;
import com.zzsn.knowbase.constant.ErrorCodeEnum;
import com.zzsn.knowbase.entity.Document; import com.zzsn.knowbase.entity.Document;
import com.zzsn.knowbase.entity.KbAuthorizedUser;
import com.zzsn.knowbase.entity.KnowFile; import com.zzsn.knowbase.entity.KnowFile;
import com.zzsn.knowbase.entity.Knowledge;
import com.zzsn.knowbase.service.DocumentService; import com.zzsn.knowbase.service.DocumentService;
import com.zzsn.knowbase.service.IKnowledgeService;
import com.zzsn.knowbase.service.ILocalFileService; import com.zzsn.knowbase.service.ILocalFileService;
import com.zzsn.knowbase.util.CodeGenerateUtil; import com.zzsn.knowbase.util.*;
import com.zzsn.knowbase.util.file.FileUtil;
import com.zzsn.knowbase.util.file.FileUtility; import com.zzsn.knowbase.util.file.FileUtility;
import com.zzsn.knowbase.util.file.Md5Utils;
import com.zzsn.knowbase.vo.Result; import com.zzsn.knowbase.vo.Result;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hashids.Hashids;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
...@@ -16,6 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -16,6 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource; import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.ui.Model; import org.springframework.ui.Model;
...@@ -52,8 +63,15 @@ public class LocalFileServiceImpl implements ILocalFileService { ...@@ -52,8 +63,15 @@ public class LocalFileServiceImpl implements ILocalFileService {
@Autowired @Autowired
private DocumentService documentService; private DocumentService documentService;
@Autowired
private IKnowledgeService knowledgeService;
@Value("${files.storage}") @Value("${files.storage}")
String filesStorage; String filesStorage;
@Value("${files.docservice.url.site}")
private String officeUrl;
@Value("${files.docservice.url.command}")
private String officeCommand;
@Override @Override
public Result<KnowFile> upload(MultipartFile file) { public Result<KnowFile> upload(MultipartFile file) {
...@@ -206,7 +224,6 @@ public class LocalFileServiceImpl implements ILocalFileService { ...@@ -206,7 +224,6 @@ public class LocalFileServiceImpl implements ILocalFileService {
} }
/** /**
* 编辑以后保存文件 * 编辑以后保存文件
* @param jsonObj * @param jsonObj
...@@ -259,6 +276,68 @@ public class LocalFileServiceImpl implements ILocalFileService { ...@@ -259,6 +276,68 @@ public class LocalFileServiceImpl implements ILocalFileService {
} }
@Override
public Result<?> editKnowledge(Knowledge knowledge) {
Result result = Result.OK();
String id = knowledge.getId();
if(id == null || "".equals(id))
return Result.error("文章id不能为空");
String publish = EsDateUtil.esFieldDateFormat(knowledge.getPublishDate());
knowledge.setPublishDate(publish);
KbAuthorizedUser userInfo = SpringContextUtils.getUserInfo();
knowledge.setUpdateBy(userInfo.getName());
knowledge.setUpdateTime(cn.hutool.core.date.DateUtil.formatDateTime(new Date()).replace(" ", "T"));
Integer verifyStatus = knowledge.getVerifyStatus();
if(verifyStatus != null && (verifyStatus == 1 || verifyStatus == 2))
knowledge.setVerifyTime(cn.hutool.core.date.DateUtil.formatDateTime(new Date()).replace(" ", "T"));
knowledge.setVerifierId(userInfo.getUserId());
knowledge.setVerifierName(userInfo.getUsername());
List<KnowFile> files = knowledge.getFiles();
KnowFile knowFile = files.get(0);
String filePath = knowFile.getFilePath();
try {
getDoucmentEditStatus(filePath);
} catch (ParseException e) {
e.printStackTrace();
result = Result.error("文件保存失败!");
}
String fileType = fileUtility.getFileType(knowFile.getFileName());
knowFile.setFileType(fileType);
File file = new File(filesStorage + knowFile.getFilePath());
Long size = file.length();
knowFile.setFileSize(size);
knowledgeService.addKnowledge(knowFile,knowledge,userInfo);
return result;
}
public ResponseEntity<Object> getDoucmentEditStatus(String filePath) throws ParseException {
String url = officeUrl+officeCommand;
Map<String,String> map = new HashMap<String,String>();
map.put("c", "forcesave");
String docFileMd5 = Md5Utils.getFileMd5(new File(filesStorage+filePath));
if (StringUtils.isBlank(docFileMd5)) {
throw new DocumentException(ErrorCodeEnum.DOC_FILE_MD5_ERROR);
}
String pathShortMd5 = Md5Utils.md5(filesStorage + filePath);
String nameShortMd5 = Md5Utils.md5(filePath);
Hashids hashids = new Hashids(DocumentConstants.HASH_KEY);
// (将路径字符串短md5值 + 名称字符串短md5值) ==> 再转成短id形式 ==> 作为文档的key(暂且认为是不会重复的)
String key = hashids.encodeHex(String.format("%s%s%s", docFileMd5,pathShortMd5, nameShortMd5));
map.put("key", key);
map.put("userdata", "sample userdata");
JSONObject obj = (JSONObject) new JSONParser().parse(FileUtil.editStatus(url, JSON.toJSONString(map)));
return new ResponseEntity<Object>(obj, HttpStatus.OK);
}
/** /**
* 文件下载 * 文件下载
*/ */
......
...@@ -305,6 +305,10 @@ public class EsOpUtil { ...@@ -305,6 +305,10 @@ public class EsOpUtil {
return docSaveByJson(index, id, JSON.toJSONString(object, SerializerFeature.WriteMapNullValue)); return docSaveByJson(index, id, JSON.toJSONString(object, SerializerFeature.WriteMapNullValue));
} }
public boolean docEditByEntity(String index, String id, Object object) {
return docUpdateById(index, id, JSON.toJSONString(object));
}
public void docSavaByEntityAsync(String index, String id, Object object) { public void docSavaByEntityAsync(String index, String id, Object object) {
docSaveByJsonAsync(index, id, JSON.toJSONString(object, SerializerFeature.WriteMapNullValue)); docSaveByJsonAsync(index, id, JSON.toJSONString(object, SerializerFeature.WriteMapNullValue));
...@@ -331,6 +335,8 @@ public class EsOpUtil { ...@@ -331,6 +335,8 @@ public class EsOpUtil {
return index; return index;
} }
/** /**
* 异步创建doc * 异步创建doc
* *
......
package com.zzsn.knowbase.util.file;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONObject;
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;
public class FileUtil {
/**
* 保存文件方法
* @param in
* @param outPath
* @throws Exception
*/
public static void saveFile(InputStream in, String outPath) throws Exception {
// FileChannel in = new FileInputStream("src/demo20/data.txt").getChannel(),
// out = new FileOutputStream("src/demo20/data2.txt").getChannel();
// in.transferTo(0, in.size(), out);
OutputStream osm = new FileOutputStream(outPath);
IOUtils.copy(in, osm);
}
/**
* 前端下载文件方法
* @param name
* @param filePath
* @param response
* @throws IOException
*/
public static void downLoadFile(String name, String filePath, HttpServletResponse response) throws IOException {
String path = filePath + name;
// path是指想要下载的文件的路径
File file = new File(path);
//log.info(file.getPath());
// 获取文件名
String filename = file.getName();
// 获取文件后缀名
String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
System.out.println("文件后缀名:" + ext);
// 将文件写入输入流
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
response.addHeader("Content-Length", "" + file.length());
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
}
/**
* 编辑以后保存文件
* @param jsonObj
* @param filePath
* @param request
* @param response
* @throws IOException
*/
public static void callBackSaveDocument(JSONObject jsonObj, String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
/*
* 当我们关闭编辑窗口后,十秒钟左右onlyoffice会将它存储的我们的编辑后的文件,,此时status = 2,通过request发给我们,我们需要做的就是接收到文件然后回写该文件。
* */
/*
* 定义要与文档存储服务保存的编辑文档的链接。当状态值仅等于2或3时,存在链路。
* */
String downloadUri = (String) jsonObj.get("url");
System.out.println("====文档编辑完成,现在开始保存编辑后的文档,其下载地址为:" + downloadUri);
//解析得出文件名
//String fileName = downloadUri.substring(downloadUri.lastIndexOf('/')+1);
String fileName = request.getParameter("fileName");
System.out.println("====下载的文件名:" + fileName);
URL url = new URL(downloadUri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
//更换为实际的路径F:\DataOfHongQuanzheng\java\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Java Example\\app_data\192.168.56.1\
//File savedFile = new File("F:\\DataOfHongQuanzheng\\onlyoffice_data\\app_data\\"+fileName);
File savedFile = new File(filePath + fileName);
if (null!=((String) jsonObj.get("userdata"))&&((String) jsonObj.get("userdata")).equals("sample userdata")) {
savedFile = new File(filePath + "v1" + fileName);
}
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();
}
/**
* 发送网路请求查看是否正在编辑
* @param path
* @param params
* @return
*/
public static String editStatus(String path, String params) {
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//发送POST请求必须设置为true
conn.setDoOutput(true);
conn.setDoInput(true);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(30000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
//获取输出流
out = new OutputStreamWriter(conn.getOutputStream());
// String jsonStr = "{\"c\":\"forcesave\", \"key\":\"WpP7m85eNQSEOoepp31oIYVG2oJyJJcvkLdoywgvs1k3ywm3Omuxk4\",\"userdata\":\"sample userdata\"}";
out.write(params);
out.flush();
out.close();
//取得输入流,并使用Reader读取
if (200 == conn.getResponseCode()) {
return IOUtils.toString(conn.getInputStream());
} else {
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return "";
}
/**
* 当最后关闭编辑界面后,将编辑时下载的文件删除
*
* @param path
* @param fileName
*/
public static void deleteTempFile(String path, String fileName) {
//因为临时存储的文件都添加了v1前缀所以删除文件时需要在文件名测前边加一个v1
File file = new File(path + "v1" + fileName);
if (file.exists()) {
file.delete();
}
}
}
package com.zzsn.knowbase; package com.zzsn.knowbase;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zzsn.knowbase.constant.Constants; import com.zzsn.knowbase.constant.Constants;
import com.zzsn.knowbase.entity.Knowledge;
import com.zzsn.knowbase.service.ILocalFileService; import com.zzsn.knowbase.service.ILocalFileService;
import com.zzsn.knowbase.util.CodeGenerateUtil; import com.zzsn.knowbase.util.CodeGenerateUtil;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
...@@ -21,6 +24,15 @@ class KnowBaseApplicationTests { ...@@ -21,6 +24,15 @@ class KnowBaseApplicationTests {
@Autowired @Autowired
private ILocalFileService localFileService; private ILocalFileService localFileService;
public static void main(String[] args) {
Knowledge knowledge = new Knowledge();
knowledge.setId("111");
knowledge.setTitle("222");
String s1 = JSON.toJSONString(knowledge, SerializerFeature.WriteMapNullValue);
String s2 = JSON.toJSONString(knowledge);
System.out.println(s2);
}
@Test @Test
void contextLoads() throws IOException { void contextLoads() throws IOException {
// ResponseEntity<Resource> re = localFileService.download("abc.docx", "E:/aaa/abc.docx"); // ResponseEntity<Resource> re = localFileService.download("abc.docx", "E:/aaa/abc.docx");
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论