wpsOffice文件在线预览-java接入
wpsOffice文件在线预览
wpsoffice开发文档地址:https://wwo.wps.cn/docs/
hint:申请服务通过后需填写回调地址,请填写你的服务器公网可访问的地址。
并且项目需要部署到你的公网可访问的服务器上。
一:添加model类
由于官方demo是完全无需引入依赖的,所以可将model包下类直接复制到自己项目中
//model类1
@Component
public class ApplicationProperties implements CommandLineRunner {public static String appid = "";public static String appSecret = "";public static String domain = "";@Autowiredpublic ApplicationProperties(@Value("${appid}") String appid,@Value("${appsecret}") String appSecret,@Value("${download_host}") String download_host,@Value("${domain}") String domain) {ApplicationProperties.appid = appid;ApplicationProperties.appSecret = appSecret;ApplicationProperties.domain = domain; TODO: 下载链接按实际情况增改参数
// if (download_host != null)
// FileModel.download_url = download_host + "/weboffice/getFile?_w_fileid=";}@Overridepublic void run(String... args) throws Exception {}
}public class FileInfoModel {FileModel file = new FileModel();UserModel user = new UserModel();}
//值是自定义的,我测试用的顺便写的参数
public class FileModel {public String id = "111";public String name = "1.doc";public long version = 3;public long size = 2000;public String creator = "1231";public String modifier = "1231";public static String download_url = "";
}public class UrlModel {public String wpsUrl;public String token;
}public class UserModel {public String id = "xxx";public String name ="xxx";public String permission = "read"; //read-在线预览 write-在线编辑public String avatar_url = "xxx";
}
二:配置文件application.yml
domain: https://wwo.wps.cn #无需改动
appid: xxx
appkey: xxx
download_host: xxx #根据需要配置
appsecret: xxx #用于加密的盐,自定义
三:实现回调接口
3.1-根据文件id生成wps的url
@RestController
public class OauthController {//自定义的ppt服务接口,用于在数据库中维护文件信息@Autowiredprivate IPptFileService pptFileService;private static Map<String, String> fileTypeMap = new HashMap<String, String>(); TODO: 参数传递最好不要出现中文等特殊字符,容易导致签名不过等问题,本例子用fileid与文件名做了一个映射,实际开发可以按情况处理static {fileTypeMap.put("1", "w");fileTypeMap.put("2", "s");fileTypeMap.put("3", "p");fileTypeMap.put("4", "f");}
// @PassToken@RequestMapping(value="/weboffice/url", method = RequestMethod.GET)@ResponseBodypublic CommonResult getapp_Token(@RequestParam("_w_fileid") String fileid) throws UnsupportedEncodingException {if (fileid == null || fileid.isEmpty()) {return null;}LambdaQueryWrapper<PptFile> queryWrapper=new LambdaQueryWrapper<>();queryWrapper.eq(PptFile::getFileKey,fileid);PptFile one = pptFileService.getOne(queryWrapper);if(one.getFileId()!=null){fileid=one.getFileId();}else{UUID uuid = UUID.randomUUID();String replace = uuid.toString().replace("-", "");one.setFileId(replace);one.setUpdateTime(new Date());fileid=replace;pptFileService.updateById(one);}String url = ApplicationProperties.domain + "/office/" + "p" + "/" + fileid + "?" ; TODO: 注意:签名前,参数不要urlencode,要签名以后统一处理url编码,防止签名不过,带中文等字符容易导致签名不过,要注意签名与编成的顺序,最好不要带中文等特殊字符Map paramMap= new HashMap<String, String>();paramMap.put("_w_appid", ApplicationProperties.appid);paramMap.put("_w_fileid", fileid);String signature = getSignature(paramMap, ApplicationProperties.appSecret);url += getUrlParam(paramMap) + "&_w_signature=" + signature;UrlModel urlModel = new UrlModel();urlModel.wpsUrl = url;urlModel.token = "abc";return CommonResult.success(urlModel);}private static String getUrlParam(Map<String, String> params) throws UnsupportedEncodingException {StringBuilder builder = new StringBuilder();for (Map.Entry<String, String> entry : params.entrySet()) {if (builder.length() > 0) {builder.append('&');}builder.append(URLEncoder.encode(entry.getKey(), "utf-8")).append('=').append(URLEncoder.encode(entry.getValue(), "utf-8"));}return builder.toString();}private static String getSignature(Map<String, String> params, String appSecret) {List<String> keys=new ArrayList();for (Map.Entry<String, String> entry : params.entrySet()) {keys.add(entry.getKey());}// 将所有参数按key的升序排序Collections.sort(keys, new Comparator<String>() {public int compare(String o1, String o2) {return o1.compareTo(o2);}});// 构造签名的源字符串StringBuilder contents=new StringBuilder("");for (String key : keys) {if (key=="_w_signature"){continue;}contents.append(key+"=").append(params.get(key));System.out.println("key:"+key+",value:"+params.get(key));}contents.append("_w_secretkey=").append(appSecret);// 进行hmac sha1 签名byte[] bytes= hmacSha1(appSecret.getBytes(),contents.toString().getBytes());//字符串经过Base64编码String sign= encodeBase64String(bytes);try {sign = URLEncoder.encode( sign, "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}System.out.println(sign);return sign;}public static byte[] hmacSha1(byte[] key, byte[] data) {try {SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");Mac mac = Mac.getInstance(signingKey.getAlgorithm());mac.init(signingKey);return mac.doFinal(data);}catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();}return null;}
}
3.2-文件信息回调接口
@RestController
public class WebOfficeController {@Autowiredprivate IPptFileService pptFileService;//我在项目中使用了腾讯云存储服务,需要了解接入腾讯云存储的朋友可看我腾讯云存储的文章//url:https://blog.csdn.net/qq_50990903/article/details/118615261?spm=1001.2014.3001.5501@Autowiredprivate QCloudStorageService storageService;@Autowiredprivate TencentCosConfig tencentCosConfig;@Autowiredprivate COSClient cosStsClient; TODO: 参数传递最好不要出现中文等特殊字符,容易导致签名不过等问题,本例子用fileid与文件名做了一个映射,实际开发可以按情况处理private static Map<String, String> fileNameMap = new HashMap<String, String>();static {fileNameMap.put("1", "中文.doc");fileNameMap.put("2", "2.xls");fileNameMap.put("3", "3.ppt");}@PassToken@RequestMapping(value="/v1/3rd/file/info", method = RequestMethod.GET)@ResponseBodypublic Object fileInfo(@RequestParam("_w_fileid") String fileid) throws Exception {JSONObject jsonObject = new JSONObject();JSONObject file = new JSONObject();JSONObject user = new JSONObject();LambdaQueryWrapper<PptFile> queryWrapper=new LambdaQueryWrapper<>();queryWrapper.eq(PptFile::getFileId,fileid);PptFile one = pptFileService.getOne(queryWrapper);try {FileModel fileModel = new FileModel(); TODO: 文件的id应该唯一file.put("id", fileid);file.put("name", fileid); TODO: 文件的版本控制file.put("version", fileModel.version); TODO: 必须返回文件真实大小,服务端会检查file.put("size", one.getFileSize());file.put("create_time",new Date().getTime()/1000);file.put("modify_time",new Date().getTime()/1000);file.put("creator", fileModel.creator);file.put("modifier", fileModel.modifier); TODO: 下载链接中的参数如带中文等特殊字符,参数必须进行urlencode//从腾讯云获取下载链接Date date = new Date(System.currentTimeMillis() + 2 * 60 * 60 * 1000);URL url = cosStsClient.generatePresignedUrl(tencentCosConfig.getQcloudBucketName(), one.getFileKey(), date);String download_url=url.toString();file.put("download_url", download_url);jsonObject.put("file", file);UserModel userModel = new UserModel();user.put("id", userModel.id);user.put("name", userModel.name);user.put("permission", "read");user.put("avatar_url", userModel.avatar_url);jsonObject.put("user", user);} catch (JSONException e) {e.printStackTrace();}return jsonObject.toString();}@PassToken@RequestMapping(value="/v1/3rd/file/version/{version}", method = RequestMethod.GET)@ResponseBodypublic Object fileVersionInfo(@PathVariable("version") Long version, @RequestParam("_w_fileid") String fileid) throws UnsupportedEncodingException {JSONObject jsonObject = new JSONObject();JSONObject file = new JSONObject();JSONObject user = new JSONObject();try {FileModel fileModel = new FileModel();File localFile = new File(fileNameMap.get(fileid));fileModel.size = localFile.length(); TODO: 文件的id应该唯一file.put("id", fileid);file.put("name", fileNameMap.get(fileid)); TODO: 文件的版本控制file.put("version", version); TODO: 必须返回文件真实大小,服务端会检查file.put("size", fileModel.size);file.put("creator", fileModel.creator);file.put("modifier", fileModel.modifier); TODO: 下载链接中的参数如带中文等特殊字符,参数必须进行urlencodefile.put("download_url", fileModel.download_url + fileid);jsonObject.put("file", file);UserModel userModel = new UserModel();user.put("id", userModel.id);user.put("name", userModel.name);user.put("permission", "write");user.put("avatar_url", userModel.avatar_url);jsonObject.put("user", user);} catch (JSONException e) {e.printStackTrace();}return jsonObject.toString();}@PassToken@RequestMapping(value="/v1/3rd/user/info", method = RequestMethod.POST)@ResponseBodypublic Object userInfo() {JSONObject jsonObject = new JSONObject();JSONArray jsonArray = new JSONArray();JSONObject user = new JSONObject();UserModel userModel = new UserModel();try {user.put("id", userModel.id);user.put("name", userModel.name);user.put("permission", userModel.permission);user.put("avatar_url", userModel.avatar_url);jsonArray.put(user);jsonObject.put("users", jsonArray);} catch (JSONException e) {e.printStackTrace();}return jsonObject.toString();}@PassToken@RequestMapping(value="/v1/3rd/file/online", method = RequestMethod.POST)@ResponseBodypublic CommonResult online() {return CommonResult.success();}@PassToken@RequestMapping(value = "/v1/3rd/file/save", method = RequestMethod.POST)@ResponseBodypublic Object save(@RequestParam("file") MultipartFile file, @RequestParam("_w_fileid") String fileid) {if (!file.isEmpty()) {try {BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(fileNameMap.get(fileid))));out.write(file.getBytes());out.flush();out.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} TODO: 返回保存后的文件信息 特别是文件大小与版本信息要准确FileModel filemodel = new FileModel();filemodel.name = fileNameMap.get(fileid);filemodel.size = file.getSize();filemodel.version = filemodel.version + 1;return filemodel;}/*** 回调通知*/@PostMapping("v1/3rd/onnotify")public CommonResult onNotify() {// logger.info("回调通知param:{}", JSON.toJSONString(obj));// TODO// 返回数据暂不处理return CommonResult.success();}/*@PassToken@GetMapping("/weboffice/getFile")public ResponseEntity<byte[]> getFile(@RequestParam("_w_fileid") String fileid) throws Exception {TODO: 处理文件下载,返回对应的文件,如果是接第三方存储,可以没有这个接口File file = new File(fileNameMap.get(fileid));InputStream inputStream = new FileInputStream(file);byte[] body = new byte[inputStream.available()];HttpHeaders headers=new HttpHeaders();headers.add("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileNameMap.get(fileid), "utf-8"));inputStream.read(body);return new ResponseEntity(body, headers, HttpStatus.OK);}*/
}
wpsOffice文件在线预览-java接入相关推荐
- java flexpaper_java web word文件 pdf文件在线预览源码(flexpaper)
[实例简介]java web word文件 pdf文件在线预览源码 经过测试 [实例截图] [核心代码] BrowsenOnline html, body{ height:100%; } body { ...
- 快速实现word、excel、ppt、txt等办公文件在线预览功能(Java版)
点击关注公众号,实用技术文章及时了解 来源:blog.csdn.net/weixin_40986713/ article/details/109527294 java实现办公文件在线预览功能是一个大家 ...
- Java 实现word、excel、ppt、txt等办公文件在线预览功能!
大家好,我是宝哥! 如何用 Java 实现word.excel.ppt.txt等办公文件在线预览功能?本文告诉你答案! java 实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司 ...
- 手把手教你用 Java 实现word、excel、ppt、txt等办公文件在线预览功能!
如何用 Java 实现word.excel.ppt.txt等办公文件在线预览功能?本文告诉你答案! java 实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司专门提供这样的服务, ...
- java将office文档,word,ppt,pdf文档转换成swf文件在线预览
java将office文档pdf文档转换成swf文件在线预览 第一步,安装openoffice.org openoffice.org是一套sun的开源office办公套件,能在widows,linux ...
- kkfileview v2.0 发布,文件在线预览项目方案
kkfileview文件在线预览 此项目为文件文档在线预览项目解决方案,项目使用流行的spring boot搭建,易上手和部署,部署好后可以独立提供预览服务,使用http接口访问,不需要和应用集成,具 ...
- Spring Boot 实现万能文件在线预览-开源学习一
Spring Boot 实现万能文件在线预览-开源学习一 1. 项目特性 支持word excel ppt,pdf等办公文档 支持txt,java,php,py,md,js,css等所有纯文本 支持z ...
- word、excel、ppt 办公文件 在线预览
如果想要免费的,可以用 openoffice,实现原理就是: 通过第三方工具openoffice,将word.excel.ppt.txt等文件转换为pdf文件流:当然如果装了Adobe Reader ...
- doc文件在线预览 vue_跨平台(uniapp)文件在线预览解决方案
一.前言 之前写过一篇文章关于上传目录文件:uni-app系统目录文件上传(非只图片和视频)解决方案,这次来解决文件预览问题. uni-app 是一个使用 Vue.js 开发所有前端应用的框架,开发者 ...
- 文件在线预览doc,docx转换pdf(一)
文件在线预览doc,docx转换pdf(一) 前言 文档转换是一个是一块硬骨头,但是也是必不可少的,我们正好做的知识库产品中,也面临着同样的问题,文档转换,精准的全文搜索,知识的转换率,是知识库产品的 ...
最新文章
- Python中if条件判断语句怎么用?
- 多媒体领域顶会--ACM MM 2020 会议论文打包下载
- codeforces 785D D. Anton and School - 2
- HDFS——HDFS+Zookeeper搭建高可用HDFS
- 搭建 mysql-mmm 高可用群集
- Flutter浪潮下的音视频研发探索
- 使用Hexo搭建博客步骤详解
- Linux常用的配置文件
- ansible-playbook Roles include
- 全站仪双棱镜测量坐标精度
- louvain算法 matlab,Community_BGLL_Matlab 复杂网络社团发现算法Louvain的 版本,简单实用,欢迎下载 272万源代码下载- www.pudn.com...
- 【历史上的今天】2 月 1 日:网景浏览器停止支持;id Software 成立;Intel 80286 芯片问世
- mysql pxc搭建_MySQL(PXC)集群搭建
- Android面试题汇总
- 【学习日记】Dom基础
- centos yum清华镜像
- Graph Coverage
- 打车代驾顺风车货车租运系统开发功能(司机端)
- 我们公司财务不接受电子发票纸质打印报销,这合理吗?
- Vulkan 简介及其特点
热门文章
- 一个例子“入坑“布谷鸟算法(附完整py代码)
- 加权平均法和移动加权法的例题
- 数学建模思路模板经典案例(看完快速入门)
- 科研计算机视觉常用绘图软件,科研图形处理——除了R、Graphpad外,这款软件也不要错过哦!...
- Switch 硬件破解经验分享 - 术语篇
- ams1117-3.3v电源稳压芯片低压差线性稳压器
- IDA的新手入门指南
- 子账号授权服务器,京东子账号装修权限之怎么授权使用详情页模板市场?
- 土地利用转移矩阵步骤
- Ubuntu20.04、22.04安装nvidia显卡驱动