附件预览分量大类,简单类型(TXT,图片,PDF),这一类的处理方法就是用浏览器解析response
office类型的复杂一些,需要安装软件等,参考链接http://my.oschina.net/baochanghong/blog/506829
这两篇文章都写得很详细,下面写一下我在项目过程中遇到的一些问题
1,使用openoffice前需要启动该服务,
CMD命令进入OpenOffice安装目录下的
program目录,键入如下命令
soffice "-accept=socket,host=localhost,port=8100;urp;StarOffice.ServiceManager" -nologo -headless -nofirststartwizard
代码
2,flexPaper只能读取根目录下的swf文件,为了不让项目文件变多,在nginx的配置文件中配置一个虚拟目录指定到本地,将Java中生成的文件放在本地,flexPaper用虚拟目录去访问
location ^~ /SwfFiles/ {
alias d:/SwfFiles/;
}
前端代码:
<
a
href
=
"http://127.0.0.1:8081/TroubleTicketServlet?servicecode=download&docName={{this.documentName}}&serialId={{../serialId}}&transDocName={{this.transDocName}}&WEB_HUB_PARAMS={'header':{'token':'','tenant':''}}"
>
Download
</
a
>
Java代码:
public
void
onlinePreview(HttpServletRequest request, HttpServletResponse response)
throws
Exception{
//本地调试打开使用
UserInfoInterface user = SessionManager. getSysUser();
if
(user ==
null
){
//servlet设置租户
user =
new
UserInfo();
user.setID(410000231);
user.setTenantId(
"21"
);
//为默认操作员设置租户ID
SessionManager. setUser(user);
}
String serialId = request.getParameter(
"serialId"
);
String transDocName = request.getParameter(
"transDocName"
);
// 必填信息校验
if
(ValidatorUtils.isEmptyId(serialId)) {
response.getWriter().write(
"serialId can not be null!"
);
return
;
}
if
(ValidatorUtils.isEmptyString(transDocName)) {
response.getWriter().write(
"transDocName can not be null!"
);
return
;
}
try
{
Map<String, String> map =
new
HashMap<String, String>();
map.put(
"serialId"
, serialId);
map.put(
"transDocName"
, transDocName);
map.put(
"pageNumber"
,
"1"
);
//页号
map.put(
"pageSize"
,
"1"
);
//分页记录数
IQueryDocInfoResponseValue docInfoResponseValue = ServiceFactoryUtils.getQryPkgHubSV().queryDocInfo(QueryConditionUtils. constructQueryConditon(map));
IDocInfoBase[] docInfoBoList = docInfoResponseValue.getResponseList();
if
(docInfoBoList ==
null
|| docInfoBoList.
length
<1){
response.getWriter().write(
"can not find file,failed to online preview!"
);
return
;
}
String docName = docInfoBoList[0].getDocumentName();
IntfLogUtils. printLogInfo(TroubleTicketServlet.
class
,
"find file:"
+ docName);
response.setHeader(
"Content-disposition"
,
"inline; filename="
+
new
String(docInfoBoList[0].getDocumentName().getBytes(
"utf-8"
),
"ISO8859-1"
));
InputStream inStream = FTPUtils.readRemote(transDocName);
//获取附件的输入流
BufferedInputStream bs=
new
BufferedInputStream(inStream);
BufferedReader ir =
new
BufferedReader(
new
InputStreamReader(bs,
"gb2312"
));
//txt
if
(docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
TXT
)){
response.setContentType(
"text/html;charset=utf-8"
);
String tmpStr =
""
;
while
((tmpStr = ir.readLine()) !=
null
){
response.getWriter().write(tmpStr+
"<br/>"
);
}
}
//图片
if
(docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
GIF
)
||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
JPEG
)
||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
JPG
)
||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
PNG
)){
response.setContentType(
"image/jpg"
);
byte
bytes[] = readInputStream(inStream);
inStream.read(bytes);
response.getOutputStream().write(bytes);
}
//PDF
if
(docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
PDF
)){
byte
bytes[] = readInputStream(inStream);
inStream.read(bytes);
response.setContentType(
"application/pdf"
);
response.getOutputStream().write(bytes);
}
//office类型
if
(docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
DOC
)
||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
DOCX
)
||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
PPT
)
||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
PPTX
)
||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
XLS
)
||docName.toLowerCase().endsWith(TroubleTicketConstant.FileType.
XLSX
)){
String dir =
"D:/SwfFiles/"
;
String suffix = docName.substring(docName.lastIndexOf(
"."
));
//.doc
File docFile =
new
File(dir+ transDocName + suffix);
FileOutputStream fop =
new
FileOutputStream(docFile);
if
(!docFile.exists()) {
docFile.createNewFile();
}
System.
out
.println(docFile.getAbsolutePath());
fop.write(readInputStream(inStream));
fop.close();
DocConverter d =
new
DocConverter(dir + transDocName + suffix, docFile);
d.conver();
String swfFileName = transDocName +
".swf"
;
response.sendRedirect(
"http://127.0.0.1:7777/ARIESRES/crm-bj/trouble-ticket/ticket-business/flexPaper/online-view.html?swfFileName="
+swfFileName);
}
inStream.close();
bs.close();
ir.close();
ServiceFactoryUtils. getBizSV().createHandlingLog(
""
, DataTypeUtils.toLong(serialId), 0, 0, TroubleTicketConstant.OperateType.
DOWNLOAD_ATTACHMENT
,
null
);
ServiceFactoryUtils. getBizSV().createDocFtpDoneLog(docInfoBoList[0].getDocumentId());
}
catch
(Exception e) {
log
.error(e,e);
response.getWriter().write(
"failed to online preview file!"
);
}
}
package com.ai.veriscrm.paas.troubleticket.common.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
public class DocConverter {
private static final int environment = 1;// 环境1:windows,2:linux(涉及pdf2swf路径问题)
private String fileString;
private String outputPath = "";// 输入路径,如果不设置就输出在默认位置
private String fileName;
private File pdfFile;
private File swfFile;
private File docFile;
public DocConverter(String fileString,File file) {
ini(fileString, file);
}
/*
* 初始化 @param fileString
*/
private void ini(String fileString, File file) {
this.fileString = fileString;
fileName = fileString.substring(0, fileString.lastIndexOf("."));
docFile = file;
pdfFile = new File(fileName + ".pdf");
swfFile = new File(fileName + ".swf");
}
/*
* 转为PDF @param file
*/
private void doc2pdf() throws Exception {
if (docFile.exists()) {
if (!pdfFile.exists()) {
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
try {
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(docFile, pdfFile);
// close the connection
connection.disconnect();
System.out.println("****pdf转换成功,PDF输出:" + pdfFile.getPath() + "****");
} catch (java.net.ConnectException e) {
// ToDo Auto-generated catch block
e.printStackTrace();
System.out.println("****swf转换异常,openoffice服务未启动!****");
throw e;
} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
e.printStackTrace();
System.out.println("****swf转换器异常,读取转换文件失败****");
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else {
System.out.println("****已经转换为pdf,不需要再进行转化****");
}
} else {
System.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****");
}
}
/*
* 转换成swf
*/
private void pdf2swf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!swfFile.exists()) {
if (pdfFile.exists()) {
if (environment == 1)// windows环境处理
{
try {
// 这里根据SWFTools安装路径需要进行相应更改
Process p = r.exec("D:/ttonline/SWFTools/pdf2swf.exe " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
System.out.print(loadStream(p.getInputStream()));
System.err.print(loadStream(p.getErrorStream()));
System.out.print(loadStream(p.getInputStream()));
System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
if (pdfFile.exists()) {
pdfFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else if (environment == 2)// linux环境处理
{
try {
Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
System.out.print(loadStream(p.getInputStream()));
System.err.print(loadStream(p.getErrorStream()));
System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
if (pdfFile.exists()) {
pdfFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
} else {
System.out.println("****pdf不存在,无法转换****");
}
} else {
System.out.println("****swf已存在不需要转换****");
}
}
static String loadStream(InputStream in) throws IOException {
int ptr = 0;
//把InputStream字节流 替换为BufferedReader字符流 2013-07-17修改
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder buffer = new StringBuilder();
while ((ptr = reader.read()) != -1) {
buffer.append((char) ptr);
}
return buffer.toString();
}
/*
* 转换主方法
*/
public boolean conver() {
if (swfFile.exists()) {
System.out.println("****swf转换器开始工作,该文件已经转换为swf****");
return true;
}
if (environment == 1) {
System.out.println("****swf转换器开始工作,当前设置运行环境windows****");
} else {
System.out.println("****swf转换器开始工作,当前设置运行环境linux****");
}
try {
doc2pdf();
pdf2swf();
} catch (Exception e) {
// TODO: Auto-generated catch block
e.printStackTrace();
return false;
}
if (swfFile.exists()) {
return true;
} else {
return false;
}
}
/*
* 返回文件路径 @param s
*/
public String getswfPath() {
if (swfFile.exists()) {
String tempString = swfFile.getPath();
tempString = tempString.replaceAll("\\\\", "/");
return tempString;
} else {
return "";
}
}
/*
* 设置输出路径
*/
public void setOutputPath(String outputPath) {
this.outputPath = outputPath;
if (!outputPath.equals("")) {
String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
if (outputPath.charAt(outputPath.length()) == '/') {
swfFile = new File(outputPath + realName + ".swf");
} else {
swfFile = new File(outputPath + realName + ".swf");
}
}
}
}
<!
DOCTYPE
html
PUBLIC
'-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
>
<
html
xmlns
=
'http://www.w3.org/1999/xhtml'
lang
=
'en'
xml:lang
=
'en'
>
<
head
>
<
title
>
FlexPaper
</
title
>
<
meta
http-equiv
=
'Content-Type'
content
=
'text/html; charset=utf-8'
/>
<
style
type
=
'text/css'
media
=
'screen'
>
html,
body
{
height
:
100%
; }
body
{
margin
:
0
;
padding
:
0
;
overflow
:
auto
; }
#flashContent
{
display
:
none
; }
</
style
>
<
script
type
=
'text/javascript'
src
=
'/ARIESRES/crm-bj/trouble-ticket/ticket-business/flexPaper/flexpaper_flash.js'
></
script
>
</
head
>
<
body
>
<
div
style
='
position
:
absolute
;
left
:
10px
;
top
:
10px
;'
>
<
a
id
=
'viewerPlaceHolder'
style
='
width
:
1300px
;
height
:
680px
;
display
:
block
'
></
a
>
<
script
type
=
'text/javascript'
>
var
str=window.location.href;
//取得整个地址栏
var
num=str.indexOf(
"?"
);
str=str.substr(num+1);
var
arr=str.split(
"&"
);
num=arr[0].indexOf(
"="
);
var
value = arr[0].substr(num+1);
var
fp =
new
FlexPaperViewer(
'FlexPaperViewer'
,
'viewerPlaceHolder'
, { config : {
SwfFile : escape(
"/SwfFiles/"
+value),
Scale : 1,
ZoomTransition :
'easeOut'
,
ZoomTime : 0.5,
ZoomInterval : 0.2,
FitPageOnLoad :
false
,
FitWidthOnLoad :
false
,
FullScreenAsMaxWindow :
false
,
ProgressiveLoading :
false
,
MinZoomSize : 0.2,
MaxZoomSize : 5,
SearchMatchAll :
true
,
InitViewMode :
'Portrait'
,
PrintPaperAsBitmap :
false
,
ViewModeToolsVisible :
true
,
ZoomToolsVisible :
true
,
NavToolsVisible :
true
,
CursorToolsVisible :
true
,
SearchToolsVisible :
false
,
localeChain:
'en_US'
}});
</
script
>
</
div
>
</
body
>
</
html
>