永中office在线编辑基于永中WebOffice的文档在线编辑能力,通过此能力,用户可以在web端直接编辑office,并且还是实时保存的,为操作office提供了许多便利。
在线编辑是通过自己搭建的服务端上传文件到永中自己的服务器之后返回响应参数,返回之后跳转到永中自己的在线编辑服务器
1,获取需要的jar
链接:https://pan.baidu.com/s/1QyjApQYJsC_xqCVr9EuMCg
提取码:7z51
2,获取sign的公共方法
/**
* 获取签名信息
*
* @param map 参数k-v
* @return 签名
* @throws Exception 异常
*/
String getSign(Map<String, String[]> map) throws Exception {
map.put("appId", new String[]{this.appId});
AppAuthenticator authenticator = new UaaAppAuthenticator(UaaConstant.SIGN, null, UaaConstant.APPID);
String sign = authenticator.generateSign(this.appKey, map);
return sign;
}
3,上传文件到永中服务器
String sign = getSign(new HashMap<>());
File file = new File("E:\\新建 Microsoft Word 文档.docx");
String urlString = httpUrl + "file/upload?appId=" + appId + "&sign=" + sign;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String Boundary = UUID.randomUUID().toString(); // 文件边界
// 1.开启Http连接
conn.setConnectTimeout(10 * 1000);
conn.setDoOutput(true); // 允许输出
// 2.Http请求行/头
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + Boundary);
// 3.Http请求体
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeUTF("--" + Boundary + "\r\n"
+ "Content-Disposition: form-data; name=file; filename=" + file.getName() + "\r\n"
+ "Content-Type: application/octet-stream; charset=utf-8" + "\r\n\r\n");
InputStream in = new FileInputStream(file);
byte[] b = new byte[1024];
int l = 0;
while ((l = in.read(b)) != -1) out.write(b, 0, l); // 写入文件
out.writeUTF("\r\n--" + Boundary + "--\r\n");
out.flush();
out.close();
in.close();
3,获取响应参数,根据参数值拼接url到永中自己的在线编辑服务器
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 4.Http响应
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = null;
StringBuffer stringBuffer = new StringBuffer();
while ((line = bf.readLine()) != null) {
System.out.println(line);
stringBuffer.append(line);
}
JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
JSONObject data = jsonObject.getJSONObject("data");
if (!"".equals(data.toJSONString()) && !"".equals(data.getString("fileVersionId"))) {
//获取返回的文件id
String fileVersionId = data.getString("fileVersionId");
//获取签名信息
Map<String, String[]> paramMap = new HashMap<>();
paramMap.put("fileVersionId", new String[]{fileVersionId});
String s = getSign(paramMap);
return "redirect:" + this.editorFileHttpUrl + "?appId=" + this.appId + "&fileVersionId=" + fileVersionId + "&sign=" + s;
}
}
配置文件值:
appId=yozotHLgsMFR5577
appKey=6879d6a56a45507f343f60be5efa
httpUrl=http://dmc.yozocloud.cn/api/
editorFileHttpUrl=http://eic.yozocloud.cn/api/edit/file
获取配置文件里面值:
@Value("${appId}")
String appId;
@Value("${appKey}")
String appKey;
@Value("${httpUrl}")
String httpUrl;
@Value("${viewFileHttpUrl}")
String viewFileHttpUrl;
实现效果图: