welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ:9167702333 邮箱:admin@xlongwei.com

doc2html 文档在线预览改进


分类 Java   关键字 分享   标签 java   web   algorithm   发布 hongwei  1449131546318
注意 转载须保留原文链接,译文链接,作者译者等信息。  
word文档在线预览接口支持上传doc文档,也支持提供文档url网址,后台还对相同的文档url做了缓存处理。

老版的接口必须上传doc文档
public JSONObject doc2html(HttpServletRequest request, MultipartFile doc)

新版的接口支持doc文档和url网址二选一,这里遇到了几个bug
1,配置参数可选,required=false。bug:仅提交url参数时报错“The current request is not a multipart request”
public JSONObject doc2html(HttpServletRequest request, @RequestParam(required=false) MultipartFile doc, @RequestParam(required=false) String url)
2,判断是否文件上传请求。bug:spring有filter处理过request了,这里再次resoveMultipart后getFile("doc")得到空值
public JSONObject doc2html(HttpServletRequest request, @RequestParam(required=false) String url) {
MultipartFile doc = multipartResolver.isMultipart(request) ? multipartResolver.resolveMultipart(request).getFile("doc") : null;
修正结果:spring处理过后的request已经是MultipartHttpServletRequest,直接可以获取到doc文档
MultipartFile doc = multipartResolver.isMultipart(request) && request instanceof MultipartHttpServletRequest ? ((MultipartHttpServletRequest)request).getFile("doc") : null;
//其实这里仅判断后一个条件就够了,从而不需要引入multipartResolver对象
MultipartFile doc = request instanceof MultipartHttpServletRequest ? ((MultipartHttpServletRequest)request).getFile("doc") : null;

对文档url参数的支持:后台下载到文件,然后再转换成html,并返回网址
String path = "doc/"+FileUtil.getFileName(url)+"_"+System.currentTimeMillis()+"."+FileUtil.getFileExt(url); 
File target = new File(GlobalConfig.getProperty(UploadUtil.uploads_temp_file), path);
boolean down = FileUtil.down(url, target);
if(down) upload = GlobalConfig.getProperty(UploadUtil.uploads_temp)+","+path;
else json.put("error", "fail to download doc from url: "+url);

缓存的支持:将结果html的网址缓存起来,下次请求检查html网址可用时即可返回
upload = CacheUtil.get("doc2html", url);
if(upload!=null && upload.indexOf(',')>-1) {
String[] paths = upload.split(",");
String domain = paths[0], path = paths[1];
if(FileUtil.exist(domain+path)) {
json.put("domain",domain);
json.put("path",path);
cached = true;
}
}
//略过一些行
if(!isDoc) CacheUtil.set("doc2html", url, domain+","+pdfPath);

get请求的支持,例如:http://cms.xlongwei.com/open/doc2html.html?url=http://cms.xlongwei.com/uploads/temp/word/test_1448934521412.doc
@RequestMapping(value="doc2html",method=RequestMethod.GET)
public String doc2html(HttpServletRequest request) {
String url = RequestUtil.getStringParam(request, "url", null);
if(StringUtil.hasLength(url)) {
JSONObject json = doc2html(request, url);
if(json.containsKey("error")) {
logger.info("fail to preview doc: "+url);
}else {
String domain = json.getString("domain");
String path = json.getString("path");
return "redirect:"+domain+path;
}
}
return "open/doc2html";
}

源码参考:OpenController
demo地址:http://cms.xlongwei.com/open/doc2html.html
另外两个接口也做了类似的改进:
文档模板填充:http://cms.xlongwei.com/open/doc2fill.html
Word文档转PDF:http://cms.xlongwei.com/open/doc2pdf.html